<?php

namespace app\api\model;

use Alipay\EasySDK\Kernel\Factory as alipayFactory;
use app\common\model\BaseModel;
use app\common\model\PlatformLog;
use EasyWeChat\Factory;
use think\db\Query;
use think\facade\Config;
use think\facade\Db;
use think\Model;

class Order extends BaseModel
{
    // 表名
    protected $name = 'order';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected $week_list = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    // 追加属性
    protected $append = [
    ];

    /**
     * 订单列表.
     */
    public function orderList($requestData, $user)
    {
        $type = $requestData['type'] ?? 0;
        $page = $requestData['page'] ?? 1;
        $limit = $requestData['limit'] ?? 0;
        $where = [['is_delete', '=', 1], ['user_id', '=', $user['id']]];
        if (!in_array($type, [0, 1, 2, 3, 4])) {
            return ['status' => 0, 'message' => '请求类型错误', 'result' => ''];
        }
        if (!$type) {
            $where[] = ['status', 'in', '1,2,3,4'];
        } else {
            $where[] = ['status', '=', $type];
        }
        $list = self::with(['order_change_pay', 'order_change_unpay', 'order_continue_pay', 'order_continue_unpay', 'order_face_pay', 'order_face_unpay'])->field('id,out_trade_no,merchant_id,merchant_car_id,start_time,end_time,days,all_money,status,send_type,car_name,car_image,merchant_car_name,shop_phone,shop_name,shop_logo,shop_address,change_status,continue_status,face_status,pick_address,return_address')->where($where)->order('createtime', 'desc')->page($page, $limit)->select()->toArray();
        if ($list) {
            foreach ($list as $key => $value) {
                $value['status_text'] = self::fetchStatus($value['status']);
                $all_money = $value['all_money'];
                if ($value['order_change_pay']) {
                    $change_money_list = array_column($value['order_change_pay'], 'diff_money');
                    $change_money = array_sum($change_money_list);
                    $all_money = bcadd($all_money, $change_money, 2);
                    $change_car_ids = [];
                    $change_car_prices = [];
                    foreach ($value['order_change_pay'] as $ks => $vs) {
                        if ($vs['merchant_car_id']) {
                            $change_car_ids[] = $vs['merchant_car_id'];
                        }
                        if ($vs['price'] > 0) {
                            $change_car_prices[] = $vs['price'];
                        }
                    }
                    if ($change_car_ids) {
                        $value['merchant_car_id'] = $change_car_ids[0];
                        $new_merchant_car = MerchantCar::field('car_id,merchant_car_name,car_price')->with('cars')->where('id', $value['merchant_car_id'])->find();
                        $value['car_name'] = $new_merchant_car['car_name'];
                        $value['car_image'] = $new_merchant_car['car_image'];
                        $value['merchant_car_name'] = $new_merchant_car['merchant_car_name'];
                    }
                    if ($change_car_prices) {
                        $value['price'] = $change_car_prices[0];
                    }
                    if ($value['order_change_pay'][0]['other_number']) {
                        $value['car_number'] = $value['order_change_pay'][0]['other_number'];
                    } else {
                        $value['car_number'] = MerchantCar::where('id', $value['order_change_pay'][0]['merchant_car_id'])->value('car_number');
                    }
                }
                if ($value['order_continue_pay']) {
                    $continue_money_list = array_column($value['order_continue_pay'], 'all_money');
                    $continue_money = array_sum($continue_money_list);
                    $all_money = bcadd($all_money, $continue_money, 2);
                    $value['end_time'] = $value['order_continue_pay'][0]['end_time'];
                }
                if ($value['order_face_pay']) {
                    $face_money_list = array_column($value['order_face_pay'], 'all_money');
                    $face_money = array_sum($face_money_list);
                    $all_money = bcadd($all_money, $face_money, 2);
                }
                $value['all_money'] = floatval($all_money);
                $value['order_change_id'] = $value['order_change_unpay']['id'] ?? '';
                $order_change_money = $value['order_change_unpay']['diff_money'] ?? '';
                $value['order_change_money'] = $order_change_money ? floatval($order_change_money) : '';
                $value['order_continue_id'] = $value['order_continue_unpay']['id'] ?? '';
                $order_continue_money = $value['order_continue_unpay']['all_money'] ?? '';
                $value['order_continue_money'] = $order_continue_money ? floatval($order_continue_money) : '';
                $value['order_face_id'] = $value['order_face_unpay']['id'] ?? '';
                $order_face_money = $value['order_face_unpay']['all_money'] ?? '';
                $value['order_face_money'] = $order_face_money ? floatval($order_face_money) : '';
                $res = getDhir($value['start_time'], $value['end_time']);
                $start_time = [
                    'day' => date('m月d日', $value['start_time']),
                    'time' => date('H:i', $value['start_time']),
                    'week' => $this->week_list[date('w', $value['start_time'])]
                ];
                $value['start_time_list'] = $start_time;
                $end_time = [
                    'day' => date('m月d日', $value['end_time']),
                    'time' => date('H:i', $value['end_time']),
                    'week' => $this->week_list[date('w', $value['end_time'])]
                ];
                if ($res['d'] > 0) {
                    $days_new = $res['h'] > 0 ? $res['d'] . '天' . $res['h'] . '小时' : $res['d'] . '小时';
                } else {
                    $days_new = $res['h'] . '小时';
                }

                $value['days_new'] = $days_new;
                $value['end_time_list'] = $end_time;
                unset($value['order_change_pay'], $value['order_change_unpay'], $value['order_continue_pay'], $value['order_continue_unpay'], $value['order_face_pay'], $value['order_face_unpay']);
                $list[$key] = $value;
            }
        }
        return ['status' => 1, 'message' => '操作成功', 'result' => $list];
    }

    /**
     * 订单详情.
     */
    public function orderDetails($requestData, $user)
    {
        $id = $requestData['id'] ?? 0;
        $where = ['is_delete' => 1, 'user_id' => $user['id'], 'id' => $id];
        $order = self::with(['order_continue', 'order_face', 'order_change_pay', 'order_change_unpay'])->field('id,out_trade_no,merchant_id,price,
        merchant_car_id,start_time,end_time,days,rental_money,deposit,all_money,
        status,deposit_status,send_type,car_name,merchant_car_name,car_number,car_image,
        car_label,car_note,shop_name,shop_logo,shop_address,shop_service,shop_phone,driver_name,
        driver_number,coupon_id,coupon_money,createtime,user_phone,shop_point,insurance,insurance_id,
        insurance_price,pay_type,deposit_type,driver_idcard_face,driver_idcard_back,driver_license_face,
        driver_license_back,start_dashboard,end_dashboard,start_check_video,end_check_video,start_check_images,
        end_check_images,start_note,pick_time,end_note,return_time,rental_contract,real_return_time,offline_money,
        offline_note,liquidated_damages,handle_fee,change_status,continue_status,face_status,pick_point,pick_address,
        return_point,return_address,refund_money,refund_time,all_change_refund_money,refund_status,cancel_time,cancel_reason,
        cancel_type,end_confirm,pick_fee,return_fee,night_pick_fee,night_return_fee,order_refund_status,order_refund_money,
        order_refund_type,order_refund_note,order_refund_addtime,distance,total_distance_price,distance_price')->where($where)->find();
//        dump($order);die;
        if (!$id || !$order) {
            return ['status' => 0, 'message' => '订单不存在', 'result' => ''];
        }
        $order = $order->toArray();
        if ($order['order_change_unpay']) {
            $order['change_order_id'] = $order['order_change_unpay']['id'];
        }
        $order['cancel_time'] = $order['cancel_time'] ? date('Y-m-d H:i:s', $order['cancel_time']) : '';
        $order['cancel_type'] = Order::fetchCancelType($order['cancel_type']);
        if ($order['order_face']) {
            foreach ($order['order_face'] as $kc => $vc) {
                $order['order_face'][$kc]['time_end'] = $vc['time_end'] ? date('Y-m-d H:i:s', $vc['time_end']) : '';
                $order['order_face'][$kc]['type'] = FaceCate::where(['is_delete' => 1, 'id' => $vc['type']])->value('name');
            }
        }
        //如果有换车订单 租赁费用 保险费用 手续费 总价 重新计算显示
        if ($order['order_change_pay']) {
            if ($order['order_continue']) {
                foreach ($order['order_continue'] as $kc => $vc) {
                    $order['order_continue'][$kc]['createtime'] = date('Y-m-d H:i:s', $vc['createtime']);
                    $order['order_continue'][$kc]['all_money'] = floatval($vc['all_money']);
                }
            }
            if ($order['order_face']) {
                foreach ($order['order_face'] as $kf => $vf) {
                    $order['order_face'][$kf]['order_face'] = date('Y-m-d H:i:s', $vf['createtime']);
                    $order['order_face'][$kf]['all_money'] = floatval($vf['all_money']);
                }
            }
            $all_money = $order['all_money'];
            $change_money_list = array_column($order['order_change_pay'], 'diff_money');
            $change_money = array_sum($change_money_list);
            $all_money = bcadd($all_money, $change_money, 2);
            $order['all_money'] = $all_money;
            $change_car_ids = [];
            $change_car_prices = [];
            $change_car_rentals = [];
            $change_car_deposits = [];
            $change_car_handles = [];
            foreach ($order['order_change_pay'] as $ks => $vs) {
                if ($vs['merchant_car_id']) {
                    $change_car_ids[] = $vs['merchant_car_id'];
                }
                if ($vs['price'] > 0) {
                    $change_car_prices[] = $vs['price'];
                }
                if ($vs['rental_money'] > 0) {
                    $change_car_rentals[] = $vs['rental_money'];
                }
                if ($vs['deposit'] > 0) {
                    $change_car_deposits[] = $vs['deposit'];
                }
                if ($vs['handle_fee'] > 0) {
                    $change_car_handles[] = $vs['handle_fee'];
                }
            }
            if ($change_car_ids) {
                $order['merchant_car_id'] = $change_car_ids[0];
                $new_merchant_car = MerchantCar::field('car_id,merchant_car_name,car_price,drive,displacement')->with('carss')->where('id', $order['merchant_car_id'])->find();
                $order['car_name'] = $new_merchant_car['car_name'];
                $order['car_image'] = $new_merchant_car['car_image'];
                $order['merchant_car_name'] = $new_merchant_car['merchant_car_name'];
                $car_gear = $new_merchant_car['car_gear'] == 1 ? '手动' : '自动';
                $order['car_label'] = $new_merchant_car['car_site'] . '座|' . $new_merchant_car['car_gate'] . '门|' . $car_gear . '|' . $new_merchant_car['displacement'];
            }
            if ($change_car_prices) {
                $order['price'] = $change_car_prices[0];
            }
            if ($change_car_rentals) {
                $order['rental_money'] = $change_car_rentals[0];
            }
            if ($change_car_deposits) {
                $order['deposit'] = $change_car_deposits[0];
            }
            if ($change_car_handles) {
                $order['handle_fee'] = $change_car_handles[0];
            }
            if ($order['order_change_pay'][0]['other_number']) {
                $order['car_number'] = $order['order_change_pay'][0]['other_number'];
            } else {
                $order['car_number'] = MerchantCar::where('id', $order['order_change_pay'][0]['merchant_car_id'])->value('car_number');
            }
        }
        $order['status_text'] = self::fetchStatus($order['status']);
        $order['change_status_text'] = self::fetchChangeStatus($order['change_status']);
        $order['continue_status_text'] = self::fetchContinueStatus($order['continue_status']);
        $order['face_status_text'] = self::fetchFaceStatus($order['face_status']);
        $res = getDhir($order['start_time'], $order['end_time']);
        if ($res['d'] > 0) {
            $days_new = $res['h'] > 0 ? $res['d'] . '天' . $res['h'] . '小时' : $res['d'] . '天';
        } else {
            $days_new = $res['h'] . '小时';
        }
        $order['price'] = floatval($order['price']);
        $order['rental_money'] = floatval($order['rental_money']);
        $order['deposit'] = floatval($order['deposit']);
        $order['all_money'] = floatval($order['all_money']);
        $order['coupon_money'] = floatval($order['coupon_money']);
        $order['insurance'] = floatval($order['insurance']);
        $order['insurance_price'] = floatval($order['insurance_price']);
        $order['offline_money'] = floatval($order['offline_money']);
        $order['liquidated_damages'] = floatval($order['liquidated_damages']);
        $order['handle_fee'] = floatval($order['handle_fee']);
        $order['all_change_refund_money'] = floatval($order['all_change_refund_money']);
        $order['pick_fee'] = floatval($order['pick_fee']);
        $order['return_fee'] = floatval($order['return_fee']);
        $order['night_pick_fee'] = floatval($order['night_pick_fee']);
        $order['night_return_fee'] = floatval($order['night_return_fee']);
        $order['order_refund_money'] = floatval($order['order_refund_money']);
        $order['days_new'] = $days_new;
        $order['start_time'] = date('m月d日 H:i', $order['start_time']);
        $order['end_time'] = date('m月d日 H:i', $order['end_time']);
        $order['send_type_text'] = self::fetchSendType($order['send_type']);
        $order['shop_service_list'] = explode(',', $order['shop_service']);
        $order['deposit_status_text'] = self::fetchDepositStatus($order['deposit_status']);
        $order['deposit_type_text'] = self::fetchDepositType($order['deposit_type']);
        $order['createtime_text'] = date('Y-m-d H:i:s', $order['createtime']);
        $shop_point = explode(',', $order['shop_point']);
        $order['longitude'] = (float)$shop_point[0];
        $order['latitude'] = (float)$shop_point[1];
        $service_phone = \app\api\model\Config::configFind(['name' => 'service_phone']);
        $order['service_phone'] = $service_phone;
        $order['start_check_images'] = explode(',', $order['start_check_images']);
        $order['end_check_images'] = explode(',', $order['end_check_images']);
        $order['pick_time'] = $order['pick_time'] ? date('Y-m-d H:i:s', $order['pick_time']) : '';
        $order['return_time'] = $order['return_time'] ? date('Y-m-d H:i:s', $order['return_time']) : '';
        $order['refund_time'] = $order['refund_time'] ? date('Y-m-d H:i:s', $order['refund_time']) : '';
        $order['order_refund_addtime'] = $order['order_refund_addtime'] ? date('Y-m-d H:i:s', $order['order_refund_addtime']) : '';
        $config = \app\api\model\Config::where('name', 'in', 'car_guarantee,cancel_time1,cancel_money1,cancel_money2,notice')->column('value', 'name');
        $order['cancel_time1'] = $config['cancel_time1'];
        $order['cancel_money1'] = $config['cancel_money1'];
        $order['cancel_money2'] = $config['cancel_money2'];
        $order['notice'] = $config['notice'];
        $order['car_guarantee'] = $config['car_guarantee'];
        $order['order_refund_type'] = RefundType::where('id', $order['order_refund_type'])->value('name');
        //租车保障
        $insure = MerchantCarInsure::field('id,insure_id,price')->with('insures')->where(['is_delete' => 1])->where('id', $order['insurance_id'])->find();
        if ($insure) {
            $insure['price'] = floatval($insure['price']);
        }
        $order['insure'] = $insure;
        $order['traffic_notice'] = Merchant::where('id', $order['merchant_id'])->value('traffic_notice');
        return ['status' => 1, 'message' => '操作成功', 'result' => $order];
    }

    /**
     * 提交订单页.
     */
    public function orderPage($requestData, $user)
    {
        $merchant_car_id = $requestData['merchant_car_id'] ?? 0;
        $merchant_id = $requestData['merchant_id'] ?? 0;
        $driver_id = $requestData['driver_id'] ?? 0;
        $start_time = $requestData['start_time'] ?? '';
        $end_time = $requestData['end_time'] ?? '';
        $pick_return_address = $requestData['pick_return_address'] ?? '';
        $pick_return_point = $requestData['pick_return_point'] ?? '';
        $merchant_insure_id = $requestData['merchant_insure_id'] ?? 0;
        $coupon_id = $requestData['coupon_id'] ?? 0;
        $deposit_type = $requestData['deposit_type'] ?? 0;
        $send_type = $requestData['send_type'] ?? 0;

        $start_lat = $requestData['start_lat'] ?? 0;
        $start_lng = $requestData['start_lng'] ?? 0;


        if (!$merchant_id || !$merchant_car_id || !$start_time || !$end_time || !$pick_return_address) {
            return ['status' => 0, 'message' => '请求错误', 'result' => ''];
        }


        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        if ($end_time <= $start_time || $end_time <= time() || $start_time <= time()) {
            return ['status' => 0, 'message' => '预约时间错误', 'result' => ''];
        }
        //商家车辆信息
        $merchant_car = MerchantCar::with('carss')->field('id,car_id,merchant_car_name,banner,car_price,car_deposit,car_note,car_number,car_label,handle_fee,night_pick_fee,night_return_fee,car_insurance,displacement,drive')->where(['id' => $merchant_car_id, 'merchant_id' => $merchant_id, 'is_delete' => 1, 'status' => 1, 'examine_status' => 2])->find();
        if (!$merchant_car) {
            return ['status' => 0, 'message' => '车辆不存在', 'result' => ''];
        }
        $merchant_car['car_price'] = floatval($merchant_car['car_price']);
        $merchant_car['car_deposit'] = floatval($merchant_car['car_deposit']);
        $merchant_car['car_note'] = $merchant_car['car_details'];
        $merchant_car['banner'] = $merchant_car['car_banner'] ? explode(',', $merchant_car['car_banner']) : [];
        $car_gear = $merchant_car['car_gear'] == 1 ? '手动挡' : '自动挡';
        $label = $merchant_car['car_site'] . '座|' . $merchant_car['car_gate'] . '门|' . $car_gear . '|' . $merchant_car['displacement'];
        $merchant_car['car_sign'] = $label;
        $labels = '';
        if ($merchant_car['car_label']) {
            $labels = Label::where('id', 'in', $merchant_car['car_label'])->column('name');
            $labels = implode(',', $labels);
        }
        $merchant_car['car_label'] = $labels;
        //保障规则和取消规则
        $config = \app\api\model\Config::where('name', 'in', 'car_guarantee,cancel_time1,cancel_money1,cancel_money2,platform_agreement,notice')->column('value', 'name');
        //商家信息
        $merchant = Merchant::getFind(['id' => $merchant_id, 'is_delete' => 1, 'status' => 1, 'examine_status' => 2], 'id,shop_name,shop_logo,Concat(province,city,area,street) as address,service,notice,traffic_notice,longitude,latitude,open_time,night_time,coupon_ids,stay_time');
        if (!$merchant) {
            return ['status' => 0, 'message' => '商家不存在', 'result' => ''];
        }
        $distance = 0;
        $total_distance_price = 0;
        $configs = (new \app\api\model\Config())->where(['id' => 42])->value('value');
        if ($send_type == 2 && $start_lat && $start_lng) {            //计算距离
            $distance = ceil($this->getDistance($merchant['latitude'], $merchant['longitude'], $start_lat, $start_lng));
            $total = $configs * $distance;
            $total_distance_price =round($total, 2) ;

        }
        $merchant['notice'] = $config['notice'];
        $merchant['service'] = explode(',', $merchant['service']);
        $start_date = date('Y-m-d', $start_time);
        $end_date = date('Y-m-d', $end_time);
        //判断商家营业时间
        $open_time = explode('-', $merchant['open_time']);
        if ($start_time < strtotime($start_date . ' ' . $open_time[0]) || $start_time > strtotime($start_date . ' ' . $open_time[1]) || $end_time < strtotime($end_date . ' ' . $open_time[0]) || $end_time > strtotime($end_date . ' ' . $open_time[1])) {
            return ['status' => 0, 'message' => '商家营业时间：' . $merchant['open_time'], 'result' => ''];
        }
        //临时下架时间
        $last_time = strtotime("-1 month");
        $merchant_car_time = MerchantCarTime::where(['is_delete' => 1, 'merchant_car_id' => $merchant_car_id])->where('end_time', '>', $last_time)->select();
        foreach ($merchant_car_time as $ke => $vl) {
            $is_time_cross = is_time_cross($vl['start_time'], $vl['end_time'], $start_time, $end_time);
            if ($is_time_cross) {
                return ['status' => 0, 'message' => '租赁时间段内商家车辆会临时下架', 'result' => ''];
            }
        }
        //判断取还车是否夜间
        $night_time = explode('-', $merchant['night_time']);
        $night_hour_list = getHours($night_time[0], $night_time[1]);
        $start_hour = date('H', $start_time);
        $end_hour = date('H', $end_time);
        $night_pick_fee = 0;
        $night_return_fee = 0;
        if (in_array($start_hour, $night_hour_list)) {
            $night_pick_fee = $merchant_car['night_pick_fee'];
        }
        if (in_array($end_hour, $night_hour_list)) {
            $night_return_fee = $merchant_car['night_return_fee'];
        }

        //判断区域 确定取车还车价格
        $pick_fee = 0;
        $return_fee = 0;
        $merchant_area = MerchantArea::field('id,price,area,stay_time')->where(['is_delete' => 1, 'status' => 1, 'merchant_id' => $merchant_id])->select()->toArray();
        $point = explode(',', $pick_return_point);
        $stay_area = false;
        foreach ($merchant_area as $kee => $vll) {
            //判断是否在区域内
            if ($vll['area']) {
                $area = getNewArea($vll['area']);
                $is_area = is_ptin_poly($point[0], $point[1], $area);
                if ($is_area) {
                    if ($start_time - time() < $vll['stay_time'] * 60) {
                        return ['status' => 0, 'message' => '该区域商家提前准备时间最少为' . $vll['stay_time'] . '分钟', 'result' => ''];
                    }
                    $stay_area = true;
                    $pick_fee = $vll['price'];
                    $return_fee = $vll['price'];
                }
            }
        }

        if (!$stay_area) {
            if ($start_time - time() < $merchant['stay_time'] * 60) {
                return ['status' => 0, 'message' => '商家提前准备时间最少为' . $merchant['stay_time'] . '分钟', 'result' => ''];
            }
        }

        //驾驶人
        $driver_where = ['user_id' => $user['id']];
        if ($driver_id) {
            $driver_where = ['id' => $driver_id];
        }
        $driver = Driver::getFind($driver_where, 'id,driver_name,driver_number');
        //租车保障
        $insure_ids = Insure::where(['is_delete' => 1, 'status' => 1])->column('id');
        $insure_list = MerchantCarInsure::field('id,insure_id,price')->with('insures')->where(['is_delete' => 1, 'merchant_car_id' => $merchant_car_id])->where('insure_id', 'in', $insure_ids)->select()->toArray();
        foreach ($insure_list as $ke => $vl) {
            $vl['active'] = 0;
            if ($merchant_insure_id && $merchant_insure_id == $vl['id']) {
                $vl['active'] = 1;
            }
            $vl['price'] = floatval($vl['price']);
            $insure_list[$ke] = $vl;
        }
        //租赁时间
        $start_list = [
            'day' => date('m月d日', $start_time),
            'time' => date('H:i', $start_time),
            'week' => $this->week_list[date('w', $start_time)],
            'start_stamp' => $start_time
        ];
        $end_list = [
            'day' => date('m月d日', $end_time),
            'time' => date('H:i', $end_time),
            'week' => $this->week_list[date('w', $end_time)],
            'end_stamp' => $end_time
        ];
        //天数
        $days = ceil(bcdiv(bcsub($end_time, $start_time, 0), 86400, 2));
        //商家车辆远期价格
        $date_list = createDateRange($requestData['start_time'], $requestData['end_time']);
        $merchant_car_price_list = MerchantCarPrice::field('start_time,end_time,price,days')->where(['is_delete' => 1, 'merchant_car_id' => $merchant_car_id])->where('end_time', '>', time())->select()->toArray();
        $new_date_list = [];
        foreach ($date_list as $kk => $vv) {
            $new_date['date'] = $vv;
            $new_date['price'] = $merchant_car['car_price'];
            foreach ($merchant_car_price_list as $kkk => $vvv) {
                if (strtotime($vv) >= $vvv['start_time'] && strtotime($vv) <= $vvv['end_time']) {
                    if ($days < $vvv['days']) {
                        return ['status' => 0, 'message' => '起租天数必须大于' . $vvv['days'], 'result' => ''];
                    }
                    $new_date['price'] = $vvv['price'];
                }
            }
            $new_date_list[] = $new_date;
        }
        $price_list = array_column($new_date_list, 'price');
        //租车费用
        $rental_money = array_sum($price_list);
        //手续费
        $handle_fee = $merchant_car['handle_fee'];
        //保险费用
        $merchant_insurance = MerchantCarInsure::where('id', $merchant_insure_id)->find();
        //押金
        $deposit = $merchant_car['car_deposit'];

        $insurance = $merchant_insurance['price'] ?? 0;
        $insurance_money = bcmul($insurance, $days, 2);
        //总费用
        $all_money = bcadd($rental_money, ($night_pick_fee + $night_return_fee + $handle_fee + $insurance_money), 2);
        //优惠券
        $coupon_money = 0;
        if ($coupon_id) {
            $user_coupon = UserCoupon::where(['is_delete' => 1, 'status' => 1])->find();
            if (!$user_coupon) {
                return ['status' => 0, 'message' => '优惠券不存在', 'result' => ''];
            }
            $coupon = Coupon::where(['is_delete' => 1, 'id' => $user_coupon['coupon_id']])->find();
            if (!$coupon) {
                return ['status' => 0, 'message' => '优惠券不存在', 'result' => ''];
            }
            if (!$coupon['status'] == 2) {
                return ['status' => 0, 'message' => '优惠券已下架', 'result' => ''];
            }
            if ($user_coupon['start_time'] > time()) {
                return ['status' => 0, 'message' => '优惠券活动未开始', 'result' => ''];
            }
            if ($user_coupon['expiration_time'] < time()) {
                return ['status' => 0, 'message' => '优惠活动已截止', 'result' => ''];
            }
            if ($user_coupon['coupon_type'] == 1) {
                if ($days < $user_coupon['coupon_limit']) {
                    return ['status' => 0, 'message' => '租赁天数不足' . $user_coupon['coupon_limit'] . '天', 'result' => ''];
                }
                $coupon_money = bcmul($user_coupon['coupon_amount'] * 0.1, $all_money, 2);
            } else {
                if ($all_money < $user_coupon['coupon_limit']) {
                    return ['status' => 0, 'message' => '支付总金额不足' . $user_coupon['coupon_limit'], 'result' => ''];
                }
                $coupon_money = $user_coupon['coupon_amount'];
            }
        }
        //我的优惠券数量
        $coupon_ids = $merchant['coupon_ids'];
        if ($coupon_ids) {
            $coupon_number = \app\api\model\UserCoupon::where(['is_delete' => 1, 'user_id' => $user['id'], 'status' => 1])->where("`type`=3 or (`type`<3 and `coupon_id` in ($coupon_ids))")->count();
        } else {
            $coupon_number = 0;
        }


        //最终费用
        $all_money = bcadd($rental_money, ($total_distance_price + $night_pick_fee + $night_return_fee + $pick_fee + $return_fee + $handle_fee + $insurance_money - $coupon_money), 2);
        //取消规则
        $data = [
            'start_time' => $start_list,
            'end_time' => $end_list,
            'days' => $days,
            'rental_money' => floatval($rental_money),
            'insurance' => floatval($insurance),
            'insurance_money' => floatval($insurance_money),
            'coupon_money' => floatval($coupon_money),
            'deposit' => floatval($deposit),
            'car_deposit' => floatval($deposit),
            'all_money' => floatval($all_money),
            'night_pick_fee' => floatval($night_pick_fee),
            'night_return_fee' => floatval($night_return_fee),
            'handle_fee' => floatval($handle_fee),
            'merchant_car' => $merchant_car,
            'merchant' => $merchant,
//            'address' => $address,
            'driver' => $driver,
            'config' => $config,
            'insure_list' => $insure_list,
            'pick_return_address' => $pick_return_address,
            'pick_return_point' => $pick_return_point,
            'coupon_number' => $coupon_number,
            'deposit_type' => $deposit_type,
            'pick_fee' => floatval($pick_fee),
            'return_fee' => floatval($return_fee),
            'distance_price' => $configs,
            'distance' => $distance,
            'total_distance_price' => $total_distance_price
        ];
        return ['status' => 1, 'message' => '操作成功', 'result' => $data];
    }

    public function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6367000; //近似地球半径（米）
        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;
        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;
        $calcLongitude = $lng2 - $lng1;     //长度
        $calcLatitude = $lat2 - $lat1;      //纬度
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $Distance = $earthRadius * $stepTwo;

        return round($Distance / 1000, 2);
    }


    /**
     *  下单支付
     */
    public function orderPay($requestData, $user)
    {
        $agreement = $requestData['agreement'] ?? 0;
        $merchant_car_id = $requestData['merchant_car_id'] ?? 0;
        $send_type = $requestData['send_type'] ?? 0;
        $user_phone = $requestData['user_phone'] ?? '';
        $merchant_id = $requestData['merchant_id'] ?? 0;
        $driver_id = $requestData['driver_id'] ?? 0;
        $start_time = $requestData['start_time'] ?? '';
        $end_time = $requestData['end_time'] ?? '';
        $deposit_type = $requestData['deposit_type'] ?? 0;
        $pick_return_address = $requestData['pick_return_address'] ?? '';
        $pick_return_point = $requestData['pick_return_point'] ?? '';
        $merchant_insure_id = $requestData['merchant_insure_id'] ?? 0;
        $coupon_id = $requestData['coupon_id'] ?? 0;

        if (!$merchant_id || !$merchant_car_id || !$send_type || !$start_time || !$end_time || !$agreement || !$deposit_type || !$pick_return_address || !$pick_return_point || !$merchant_insure_id) {
            return ['status' => 0, 'message' => '请求错误', 'result' => ''];
        }
        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        if ($agreement != 1) {
            return ['status' => 0, 'message' => '请选择同意《平台协议》', 'result' => ''];
        }
        if ($user['is_certified'] != 3) {
            return ['status' => 0, 'message' => '请先实名认证', 'result' => ''];
        }
        if ($start_time >= $end_time) {
            return ['status' => 0, 'message' => '结束时间不能大于开始时间', 'result' => ''];
        }
        if ($start_time <= time() || $end_time <= time()) {
            return ['status' => 0, 'message' => '租赁时间错误', 'result' => ''];
        }
        Db::startTrans();
        try {
            if (!$user_phone || !preg_match('/^1[3456789]\d{9}$/ims', $user_phone)) {
                return ['status' => 0, 'message' => '用户手机号错误', 'result' => ''];
            }
            //商家车辆信息
            $merchant_car = MerchantCar::getFind(['id' => $merchant_car_id, 'merchant_id' => $merchant_id, 'is_delete' => 1, 'status' => 1, 'examine_status' => 2]);
            if (!$merchant_car) {
                return ['status' => 0, 'message' => '车辆不存在', 'result' => ''];
            }
            $car = Car::getFind(['id' => $merchant_car['car_id']]);
            if (!$car) {
                return ['status' => 0, 'message' => '车辆不存在', 'result' => ''];
            }
            //商家信息
            $merchant = Merchant::getFind(['id' => $merchant_id, 'is_delete' => 1, 'status' => 1, 'examine_status' => 2]);
            if (!$merchant) {
                return ['status' => 0, 'message' => '商家不存在', 'result' => ''];
            }
            //驾驶人
            $driver = Driver::getFind(['id' => $driver_id]);
            if (!$driver) {
                return ['status' => 0, 'message' => '驾驶人不存在', 'result' => ''];
            }
            //判断同一时间段内同一驾驶人只能有一单
            $driver_order = self::field('id,start_time,end_time')->where(['is_delete' => 1, 'driver_id' => $driver['driver_id'], 'status' => [1, 2]])->where("(start_time>=$start_time and end_time<=$end_time) or (start_time<=$start_time and end_time>=$end_time) or (start_time>$start_time and start_time<$end_time) or (end_time>$start_time and end_time<$end_time)")->count();
            if ($driver_order) {
                return ['status' => 0, 'message' => '该时间段内该驾驶人已有订单', 'result' => ''];
            }
            //订单频繁提交
            $old_order = self::field('id,createtime')->where(['user_id' => $user['id']])->order('createtime', 'desc')->lock(true)->find();
            if ($old_order) {
                $time_slot = bcsub(time(), $old_order['createtime'], 0);
                if ($time_slot <= 10) {
                    return ['status' => 0, 'message' => '提交过于频繁', 'result' => ''];
                }
            }
            $start_date = date('Y-m-d', $start_time);
            $end_date = date('Y-m-d', $end_time);
            //判断商家营业时间
            $open_time = explode('-', $merchant['open_time']);
            if ($start_time < strtotime($start_date . ' ' . $open_time[0]) || $start_time > strtotime($start_date . ' ' . $open_time[1]) || $end_time < strtotime($end_date . ' ' . $open_time[0]) || $end_time > strtotime($end_date . ' ' . $open_time[1])) {
                return ['status' => 0, 'message' => '商家营业时间：' . $open_time, 'result' => ''];
            }

            //临时下架时间
            $last_time = strtotime("-1 month");
            $merchant_car_time = MerchantCarTime::where(['is_delete' => 1, 'merchant_car_id' => $merchant_car_id])->where('end_time', '>', $last_time)->select();
            foreach ($merchant_car_time as $ke => $vl) {
                $is_time_cross = is_time_cross($vl['start_time'], $vl['end_time'], $start_time, $end_time);
                if ($is_time_cross) {
                    return ['status' => 0, 'message' => '租赁时间段内商家车辆会临时下架', 'result' => ''];
                }
            }

            //判断取还车是否夜间
            $night_time = explode('-', $merchant['night_time']);
            $night_hour_list = getHours($night_time[0], $night_time[1]);
            $start_hour = date('H', $start_time);
            $end_hour = date('H', $end_time);
            $night_pick_fee = 0;
            $night_return_fee = 0;
            if (in_array($start_hour, $night_hour_list)) {
                $night_pick_fee = $merchant_car['night_pick_fee'];
            }
            if (in_array($end_hour, $night_hour_list)) {
                $night_return_fee = $merchant_car['night_return_fee'];
            }

            //判断区域 确定取车还车价格
            $pick_fee = 0;
            $return_fee = 0;
            $stay_area = false;
            $merchant_area = MerchantArea::field('id,price,area,stay_time')->where(['is_delete' => 1, 'status' => 1, 'merchant_id' => $merchant_id])->select()->toArray();
            $point = explode(',', $pick_return_point);
            foreach ($merchant_area as $kee => $vll) {
                //判断是否在区域内
                if ($vll['area']) {
                    $area = getNewArea($vll['area']);
                    $is_area = is_ptin_poly($point[0], $point[1], $area);
                    if ($is_area) {
                        if ($start_time - time() < $vll['stay_time'] * 60) {
                            return ['status' => 0, 'message' => '改区域商家提前准备时间最少为' . $vll['stay_time'] . '分钟', 'result' => ''];
                        }
                        $pick_fee = $vll['price'];
                        $return_fee = $vll['price'];
                        $stay_area = true;
                    }
                }
            }

            if (!$stay_area) {
                if ($start_time - time() < $merchant['stay_time'] * 60) {
                    return ['status' => 0, 'message' => '商家提前准备时间最少为' . $merchant['stay_time'] . '分钟', 'result' => ''];
                }
            }

            //天数
            $days = ceil(bcdiv(bcsub($end_time, $start_time, 0), 86400, 2));
            //商家车辆远期价格
            $date_list = createDateRange($requestData['start_time'], $requestData['end_time']);
            $merchant_car_price_list = MerchantCarPrice::field('start_time,end_time,price,days')->where(['is_delete' => 1, 'merchant_car_id' => $merchant_car_id])->where('end_time', '>', time())->select()->toArray();
            $new_date_list = [];
            if ($merchant_car_price_list) {
                foreach ($date_list as $kk => $vv) {
                    $new_date['date'] = $vv;
                    $new_date['price'] = $merchant_car['car_price'];
                    foreach ($merchant_car_price_list as $kkk => $vvv) {
                        if (strtotime($vv) >= $vvv['start_time'] && strtotime($vv) <= $vvv['end_time']) {
                            if ($days < $vvv['days']) {
                                return ['status' => 0, 'message' => '起租天数必须大于' . $vvv['days'], 'result' => ''];
                            }
                            $new_date['price'] = $vvv['price'];
                        }
                    }
                    $new_date_list[] = $new_date;
                }
                $price_list = array_column($new_date_list, 'price');
                $prices = implode(',', $price_list);
                //租车费用
                $rental_money = array_sum($price_list);
                //平均单价
                $car_price = $merchant_car['car_price'];
            } else {
                $car_price = $merchant_car['car_price'];
                $prices = $merchant_car['car_price'];
                $rental_money = bcmul($merchant_car['car_price'], $days, 2);
            }

            if ($rental_money < 0.01) {
                return ['status' => 0, 'message' => '租车费用必须大于0.01', 'result' => ''];
            }
            //手续费
            $handle_fee = $merchant_car['handle_fee'];
            //保险费用
            $merchant_insurance = MerchantCarInsure::where('id', $merchant_insure_id)->find();
            $insurance = $merchant_insurance['price'] ?? 0;
            $insurance_money = bcmul($insurance, $days, 2);
            //押金
            $car_deposit = $merchant_car['car_deposit'];
            //优惠券
            $coupon_money = 0;
            if ($coupon_id) {
                $user_coupon = UserCoupon::where(['is_delete' => 1, 'status' => 1, 'id' => $coupon_id])->find();
                if (!$user_coupon) {
                    return ['status' => 0, 'message' => '优惠券不存在', 'result' => ''];
                }
                $coupon = Coupon::where(['is_delete' => 1, 'id' => $user_coupon['coupon_id']])->find();
                if (!$coupon) {
                    return ['status' => 0, 'message' => '优惠券不存在', 'result' => ''];
                }
                if (!$coupon['status'] == 2) {
                    return ['status' => 0, 'message' => '优惠券已下架', 'result' => ''];
                }
                if ($user_coupon['start_time'] > time()) {
                    return ['status' => 0, 'message' => '优惠券活动未开始', 'result' => ''];
                }
                if ($user_coupon['expiration_time'] < time()) {
                    return ['status' => 0, 'message' => '优惠活动已截止', 'result' => ''];
                }
                if ($user_coupon['coupon_type'] == 1) {
                    if ($days < $user_coupon['coupon_limit']) {
                        return ['status' => 0, 'message' => '租赁天数不足' . $user_coupon['coupon_limit'] . '天', 'result' => ''];
                    }
                    $coupon_money = bcmul($user_coupon['coupon_amount'] * 0.1, $rental_money, 2);
                } else {
                    if ($rental_money < $user_coupon['coupon_limit']) {
                        return ['status' => 0, 'message' => '租赁金额不足' . $user_coupon['coupon_limit'], 'result' => ''];
                    }
                    if ($user_coupon['type'] == 2) {//折扣券
                        $coupon_money = $user_coupon['coupon_amount'];
                    } else {
                        $coupon_money = bcmul($rental_money, (1 - $user_coupon['coupon_amount'] * 0.1), 2);
                    }
                    if ($coupon_money < $rental_money) {
                        return ['status' => 0, 'message' => '租赁金额不能小于优惠金额', 'result' => ''];
                    }
                }
            }
            //计算距离价格
            $send_type = $requestData['send_type'] ?? 0;
            $start_lat = $requestData['start_lat'] ?? 0;
            $start_lng = $requestData['start_lng'] ?? 0;

            $distance = 0;
            $total_distance_price = 0;
            $configs = (new \app\api\model\Config())->where(['id' => 42])->value('value');
            if ($send_type == 2 && $start_lat && $start_lng) {
                //计算距离
                $distance = ceil($this->getDistance($merchant['latitude'], $merchant['longitude'], $start_lat, $start_lng));
                $total = $configs * $distance;
                $total_distance_price =round($total, 2) ;

            }


            //总费用
            $all_money = bcadd($rental_money, ($total_distance_price + $night_pick_fee + $night_return_fee + $handle_fee + $insurance_money + $pick_fee + $return_fee - $coupon_money), 2);
            $car_gear = $car['car_gear'] == 1 ? '手动挡' : '自动挡';
            $car_label = $car['car_site'] . '座|' . $car['car_gate'] . '门|' . $car_gear . '|' . $merchant_car['displacement'];
            $address_street = (isset($address) && $address) ? $address['province'] . $address['city'] . $address['area'] . $address['street'] : '';
            $pay_type = $user['user_type'];

            $order = [
                'distance' => $distance,
                'total_distance_price' => $total_distance_price,
                'distance_price'=>$configs,
                'user_id' => $user['id'],
                'out_trade_no' => self::getOutTradeNo(),
                'merchant_car_id' => $merchant_car_id,
                'merchant_id' => $merchant_id,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'days' => $days,
                'price' => $car_price,
                'rental_money' => $rental_money,
                'deposit' => $car_deposit,
                'all_money' => $all_money,
                'deposit_status' => $car_deposit > 0 ? 1 : 0,
                'send_type' => $send_type,
                'car_image' => $car['car_image'],
                'car_name' => $car['car_name'],
                'car_number' => $merchant_car['car_number'],
                'merchant_car_name' => $merchant_car['merchant_car_name'],
                'car_label' => $car_label,
                'car_note' => $merchant_car['car_note'],
                'shop_name' => $merchant['shop_name'],
                'shop_logo' => $merchant['shop_logo'],
                'shop_address' => $merchant['province'] . $merchant['city'] . $merchant['area'] . $merchant['street'],
                'shop_service' => $merchant['service'],
                'driver_id' => $driver_id,
                'driver_name' => $driver['driver_name'],
                'driver_number' => $driver['driver_number'],
                'address_name' => $address['address_name'] ?? '',
                'address_phone' => $address['address_phone'] ?? '',
                'address_street' => $address_street,
                'createtime' => time(),
                'user_phone' => $user_phone,
                'shop_point' => $merchant['longitude'] . ',' . $merchant['latitude'],
                'insurance' => $insurance_money,
                'insurance_id' => $merchant_insure_id,
                'insurance_price' => $merchant_insurance['price'],
                'shop_phone' => $merchant['merchant_phone'],
                'pay_type' => $pay_type,
                'deposit_type' => $deposit_type,
                'handle_fee' => $handle_fee,
                'pick_point' => $pick_return_point,
                'return_point' => $pick_return_point,
                'pick_address' => $pick_return_address,
                'return_address' => $pick_return_address,
                'prices' => $prices,
                'night_pick_fee' => $night_pick_fee,
                'night_return_fee' => $night_return_fee,
                'last_all_money' => $all_money,
                'pick_fee' => $pick_fee,
                'return_fee' => $return_fee,
            ];
            $order_id = self::insertGetId($order);
            $order['id'] = $order_id;
            //去支付
            if ($pay_type == 1) {//微信支付
                $result = self::Pay($order, $user, 'orderNotify');
            } else {//支付宝支付
                $result = self::aliPay($order, $user, 'orderAlipayNotify');
            }
            Db::commit();
            if ($result) {
                $result['order_id'] = $order_id;
                return ['status' => 1, 'message' => '请求成功', 'result' => $result];
            } else {
                return ['status' => 0, 'message' => '请求失败', 'result' => ''];
            }
        } catch (Exception $e) {
            Db::rollback();
            return ['status' => 1, 'message' => $e->getMessage(), 'result' => ''];
        }
    }

    /**
     *  取消支付接口
     */
    public function cancelPay($requestData, $user)
    {
        $order = self::getFind(['user_id' => $user['id'], 'is_delete' => 1, 'status' => 0]);
        if (!$order) {
            return ['status' => 0, 'message' => '订单不存在', 'result' => ''];
        }
        Db::startTrans();
        try {
            self::where('id', $order['id'])->update(['is_delete' => 2, 'deletetime' => time()]);
            Db::commit();
            return ['status' => 1, 'message' => '请求成功', 'result' => ''];
        } catch (Exception $e) {
            Db::rollback();
            return ['status' => 0, 'message' => $e->getMessage(), 'result' => ''];
        }
    }

    /**
     *  取消预约
     */
    public function orderRefund($requestData, $user)
    {
        $order_id = $requestData['order_id'] ?? 0;
        $cancel_type = $requestData['cancel_type'] ?? 0;
        $cancel_reason = $requestData['cancel_reason'] ?? '';
        if (!$order_id || !$cancel_type) {
            return ['status' => 0, 'message' => '参数错误', 'result' => ''];
        }
        $order = Order::with(['order_change_payed', 'order_continue_payed', 'order_face_payed'])->where(['id' => $order_id, 'user_id' => $user['id'], 'is_delete' => 1, 'status' => 1])->find();
        if (!$order) {
            return ['status' => 0, 'message' => '订单不存在', 'result' => ''];
        }
        $order = $order->toArray();
        //判断是否扣款
        $config = \app\api\model\Config::where('name', 'in', 'cancel_time1,cancel_money1,cancel_money2')->column('value', 'name');
        $cancel_rate = 0;//扣款比例
        $cancel_time = $config['cancel_time1'] * 3600;
        if (time() + $cancel_time >= $order['start_time'] && time() < $order['start_time']) {
            $cancel_rate = $config['cancel_money1'] / 100;
        } elseif (time() > $order['start_time']) {
            $cancel_rate = $config['cancel_money2'] / 100;
        }
        $merchant = Merchant::where('id', $order['merchant_id'])->find();
        Db::startTrans();
        try {
            $merchant_liquidated_money = [];
            if ($cancel_rate < 1) {
                if ($order['pay_type'] == 1) {//微信
                    //主订单退款
                    $liquidated_damages = bcmul($cancel_rate, $order['last_all_money'], 2);
                    $refund_money = bcsub($order['last_all_money'], $liquidated_damages, 2);
                    if ($merchant['cancel_rate'] > 0 && $liquidated_damages > 0) {
                        //取消订单商家余额增加
                        $merchant_liquidated_money[] = bcmul($refund_money, $merchant['cancel_rate'] / 100, 2);
                    }
                    $order['refund_money'] = $refund_money;
                    $update = ['status' => 4, 'cancel_time' => time(), 'cancel_type' => $cancel_type, 'cancel_reason' => $cancel_reason];
                    if ($order['deposit_status'] == 1 && $order['deposit'] > 0) {
                        $update['deposit_status'] = 2;
                    }
                    $out_refund_no = self::getOutRefundNo();
                    $order['out_refund_no'] = $out_refund_no;
                    $res = self::refund($order, $user);
                    if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
                        $update['out_refund_no'] = $out_refund_no;
                        $update['refund_id'] = $res['refund_id'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                        $update['liquidated_damages'] = $liquidated_damages;
                        $all_refund_money = bcadd($order['all_refund_money'], $refund_money, 2);
                        $last_all_money = bcsub($order['last_all_money'], $refund_money, 2);
                        if ($last_all_money < 0) $last_all_money = 0;
                        if ($all_refund_money > $order['all_money']) $all_refund_money = $order['all_money'];
                        $update['all_refund_money'] = $all_refund_money;
                        $update['last_all_money'] = $last_all_money;
                        $update['all_refund_number'] = $order['all_refund_number'] ? $order['all_refund_number'] . ',' . $out_refund_no : $out_refund_no;
                        $result = self::where('id', $order_id)->update($update);
                        //车状态修改
                        MerchantCar::where('id', $order['merchant_car_id'])->update(['car_status' => 1]);
                        //写入平台流水
                        $platform_log = [
                            'user_id' => $user['id'],
                            'amount' => $order['all_money'],
                            'type' => 3,
                            'log_note' => '取消预约退款',
                            'order_id' => $order['id'],
                            'order_type' => 1,
                            'createtime' => time(),
                        ];
                        PlatformLog::insert($platform_log);
                    } else {
                        Db::rollback();
                        return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                    }

                    //换车订单退款
                    $order_change_payed = $order['order_change_payed'];
                    if ($order_change_payed) {
                        foreach ($order_change_payed as $key => $value) {
                            $liquidated_damages = bcmul($cancel_rate, $value['last_all_money'], 2);
                            $refund_money = bcsub($value['last_all_money'], $liquidated_damages, 2);
                            if ($merchant['cancel_rate'] > 0 && $liquidated_damages > 0) {
                                //取消订单商家余额增加
                                $merchant_liquidated_money[] = bcmul($refund_money, $merchant['cancel_rate'] / 100, 2);
                            }
                            $value['refund_money'] = $refund_money;
                            $update = ['pay_status' => 3, 'cancel_time' => time()];
                            if ($value['deposit_status'] == 1 && $value['deposit'] > 0) {
                                $update['deposit_status'] = 2;
                            }
                            $out_refund_no = self::getOutRefundNo('order_change');
                            $value['out_refund_no'] = $out_refund_no;
                            $res = self::refund($value, $user);
                            if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
                                $update['out_refund_no'] = $out_refund_no;
                                $update['refund_id'] = $res['refund_id'];
                                $update['refund_time'] = time();
                                $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                $update['liquidated_damages'] = $liquidated_damages;
                                $all_refund_money = bcadd($value['all_refund_money'], $refund_money, 2);
                                $last_all_money = bcsub($value['last_all_money'], $refund_money, 2);
                                if ($last_all_money < 0) $last_all_money = 0;
                                if ($all_refund_money > $value['all_money']) $all_refund_money = $value['all_money'];
                                $update['all_refund_money'] = $all_refund_money;
                                $update['last_all_money'] = $last_all_money;
                                $result = OrderChange::where('id', $value['id'])->update($update);
                                //写入平台流水
                                $platform_log = [
                                    'user_id' => $user['id'],
                                    'amount' => $value['refund_money'],
                                    'type' => 7,
                                    'log_note' => '取消预约换车订单退款',
                                    'order_id' => $value['id'],
                                    'order_type' => 1,
                                    'createtime' => time(),
                                    'total_order_id' => $order['id']
                                ];
                                PlatformLog::insert($platform_log);
                            } else {
                                Db::rollback();
                                return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                            }
                        }
                    }

                    //续租订单退款
                    $order_continue_payed = $order['order_continue_payed'];
                    if ($order_continue_payed) {
                        foreach ($order_continue_payed as $k => $v) {
                            $liquidated_damages = bcmul($cancel_rate, $v['last_all_money'], 2);
                            $refund_money = bcsub($v['last_all_money'], $liquidated_damages, 2);
                            if ($merchant['cancel_rate'] > 0 && $liquidated_damages > 0) {
                                //取消订单商家余额增加
                                $merchant_liquidated_money[] = bcmul($refund_money, $merchant['cancel_rate'] / 100, 2);
                            }
                            $v['refund_money'] = $refund_money;
                            $update = ['pay_status' => 3, 'cancel_time' => time()];
                            if ($v['deposit_status'] == 1 && $v['deposit'] > 0) {
                                $update['deposit_status'] = 2;
                            }
                            $out_refund_no = self::getOutRefundNo('order_continue');
                            $v['out_refund_no'] = $out_refund_no;
                            $res = self::refund($v, $user);
                            if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
                                $update['out_refund_no'] = $out_refund_no;
                                $update['refund_id'] = $res['refund_id'];
                                $update['refund_time'] = time();
                                $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                $update['liquidated_damages'] = $liquidated_damages;
                                $all_refund_money = bcadd($v['all_refund_money'], $refund_money, 2);
                                $last_all_money = bcsub($v['last_all_money'], $refund_money, 2);
                                if ($last_all_money < 0) $last_all_money = 0;
                                if ($all_refund_money > $v['all_money']) $all_refund_money = $v['all_money'];
                                $update['all_refund_money'] = $all_refund_money;
                                $update['last_all_money'] = $last_all_money;
                                $result = OrderContinue::where('id', $v['id'])->update($update);
                                //写入平台流水
                                $platform_log = [
                                    'user_id' => $user['id'],
                                    'amount' => $v['refund_money'],
                                    'type' => 9,
                                    'log_note' => '取消预约续租订单退款',
                                    'order_id' => $v['id'],
                                    'order_type' => 1,
                                    'createtime' => time(),
                                    'total_order_id' => $order['id']
                                ];
                                PlatformLog::insert($platform_log);
                            } else {
                                Db::rollback();
                                return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                            }
                        }
                    }

                    //当面付订单退款
                    $order_face_payed = $order['order_face_payed'];
                    if ($order_face_payed) {
                        foreach ($order_face_payed as $kk => $vv) {
                            $liquidated_damages = bcmul($cancel_rate, $vv['last_all_money'], 2);
                            $refund_money = bcsub($vv['last_all_money'], $liquidated_damages, 2);
                            if ($merchant['cancel_rate'] > 0 && $liquidated_damages > 0) {
                                //取消订单商家余额增加
                                $merchant_liquidated_money[] = bcmul($refund_money, $merchant['cancel_rate'] / 100, 2);
                            }
                            $vv['refund_money'] = $refund_money;
                            $update = ['pay_status' => 3, 'cancel_time' => time()];
                            if ($vv['deposit_status'] == 1 && $vv['deposit'] > 0) {
                                $update['deposit_status'] = 2;
                            }
                            $out_refund_no = self::getOutRefundNo('order_face');
                            $vv['out_refund_no'] = $out_refund_no;
                            $res = self::refund($vv, $user);
                            if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
                                $update['out_refund_no'] = $out_refund_no;
                                $update['refund_id'] = $res['refund_id'];
                                $update['refund_time'] = time();
                                $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                $update['liquidated_damages'] = $liquidated_damages;
                                $all_refund_money = bcadd($vv['all_refund_money'], $refund_money, 2);
                                $last_all_money = bcsub($vv['last_all_money'], $refund_money, 2);
                                if ($last_all_money < 0) $last_all_money = 0;
                                if ($all_refund_money > $vv['all_money']) $all_refund_money = $vv['all_money'];
                                $update['all_refund_money'] = $all_refund_money;
                                $update['last_all_money'] = $last_all_money;
                                $result = OrderFace::where('id', $vv['id'])->update($update);
                                //写入平台流水
                                $platform_log = [
                                    'user_id' => $user['id'],
                                    'amount' => $vv['refund_money'],
                                    'type' => 11,
                                    'log_note' => '取消预约当面付订单退款',
                                    'order_id' => $vv['id'],
                                    'order_type' => 1,
                                    'createtime' => time(),
                                    'total_order_id' => $order['id']
                                ];
                                PlatformLog::insert($platform_log);
                            } else {
                                Db::rollback();
                                return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                            }
                        }
                    }
                } else {//支付宝
                    //主订单退款
                    $liquidated_damages = bcmul($cancel_rate, $order['last_all_money'], 2);
                    $refund_money = bcsub($order['last_all_money'], $liquidated_damages, 2);
                    if ($merchant['cancel_rate'] > 0 && $liquidated_damages > 0) {
                        //取消订单商家余额增加
                        $merchant_liquidated_money[] = bcmul($refund_money, $merchant['cancel_rate'] / 100, 2);
                    }
                    $order['refund_money'] = $refund_money;
                    $update = ['status' => 4, 'cancel_time' => time()];
                    if ($order['deposit_status'] == 1 && $order['deposit'] > 0) {
                        $update['deposit_status'] = 2;
                    }
                    $out_refund_no = self::getOutRefundNo();
                    $order['out_refund_no'] = $out_refund_no;
                    $res = self::alipayrefund($order, $user);
                    if ($res['code'] == '10000') {
                        $update['out_refund_no'] = $order['out_refund_no'];
                        $update['refund_id'] = $res['trade_no'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = $res['refund_fee'];
                        $update['liquidated_damages'] = $liquidated_damages;
                        $all_refund_money = bcadd($order['all_refund_money'], $refund_money, 2);
                        $last_all_money = bcsub($order['last_all_money'], $refund_money, 2);
                        if ($last_all_money < 0) $last_all_money = 0;
                        if ($all_refund_money > $order['all_money']) $all_refund_money = $order['all_money'];
                        $update['all_refund_money'] = $all_refund_money;
                        $update['last_all_money'] = $last_all_money;
                        $update['all_refund_number'] = $order['all_refund_number'] ? $order['all_refund_number'] . ',' . $out_refund_no : $out_refund_no;
                        $result = self::where('id', $order_id)->update($update);
                        //车状态修改
                        MerchantCar::where('id', $order['merchant_car_id'])->update(['car_status' => 1]);
                        //写入平台流水
                        $platform_log = [
                            'user_id' => $user['id'],
                            'amount' => $order['all_money'],
                            'type' => 3,
                            'log_note' => '取消预约退款',
                            'order_id' => $order['id'],
                            'order_type' => 1,
                            'createtime' => time(),
                        ];
                        PlatformLog::insert($platform_log);
                    } else {
                        Db::rollback();
                        return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                    }

                    //换车订单退款
                    $order_change_payed = $order['order_change_payed'];
                    if ($order_change_payed) {
                        foreach ($order_change_payed as $kc => $vc) {
                            $liquidated_damages = bcmul($cancel_rate, $vc['last_all_money'], 2);
                            $refund_money = bcsub($vc['last_all_money'], $liquidated_damages, 2);
                            if ($merchant['cancel_rate'] > 0 && $liquidated_damages > 0) {
                                //取消订单商家余额增加
                                $merchant_liquidated_money[] = bcmul($refund_money, $merchant['cancel_rate'] / 100, 2);
                            }
                            $vc['refund_money'] = $refund_money;
                            $update = ['pay_status' => 3, 'cancel_time' => time()];
                            if ($vc['deposit_status'] == 1 && $vc['deposit'] > 0) {
                                $update['deposit_status'] = 2;
                            }
                            $out_refund_no = self::getOutRefundNo('order_change');
                            $vc['out_refund_no'] = $out_refund_no;
                            $res = self::alipayrefund($vc, $user);
                            if ($res['code'] == '10000') {
                                $update['out_refund_no'] = $out_refund_no;
                                $update['refund_id'] = $res['trade_no'];
                                $update['refund_time'] = time();
                                $update['refund_money'] = $res['refund_fee'];
                                $update['liquidated_damages'] = $liquidated_damages;
                                $result = OrderChange::where('id', $vc['id'])->update($update);
                                //写入平台流水
                                $platform_log = [
                                    'user_id' => $user['id'],
                                    'amount' => $vc['refund_money'],
                                    'type' => 7,
                                    'log_note' => '取消预约换车订单退款',
                                    'order_id' => $vc['id'],
                                    'order_type' => 1,
                                    'createtime' => time(),
                                    'total_order_id' => $order['id']
                                ];
                                PlatformLog::insert($platform_log);
                            } else {
                                Db::rollback();
                                return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                            }
                        }
                    }

                    //续租订单退款
                    $order_continue_payed = $order['order_continue_payed'];
                    if ($order_continue_payed) {
                        foreach ($order_continue_payed as $kn => $vn) {
                            $liquidated_damages = bcmul($cancel_rate, $vn['last_all_money'], 2);
                            $refund_money = bcsub($vn['last_all_money'], $liquidated_damages, 2);
                            if ($merchant['cancel_rate'] > 0 && $liquidated_damages > 0) {
                                //取消订单商家余额增加
                                $merchant_liquidated_money[] = bcmul($refund_money, $merchant['cancel_rate'] / 100, 2);
                            }
                            $vn['refund_money'] = $refund_money;
                            $update = ['pay_status' => 3, 'cancel_time' => time()];
                            if ($vn['deposit_status'] == 1 && $vn['deposit'] > 0) {
                                $update['deposit_status'] = 2;
                            }
                            $out_refund_no = self::getOutRefundNo('order_continue');
                            $vn['out_refund_no'] = $out_refund_no;
                            $res = self::alipayrefund($vn, $user);
                            if ($res['code'] == '10000') {
                                $update['out_refund_no'] = $out_refund_no;
                                $update['refund_id'] = $res['trade_no'];
                                $update['refund_time'] = time();
                                $update['refund_money'] = $res['refund_fee'];
                                $update['liquidated_damages'] = $liquidated_damages;
                                $result = OrderContinue::where('id', $vn['id'])->update($update);
                                //写入平台流水
                                $platform_log = [
                                    'user_id' => $user['id'],
                                    'amount' => $vn['refund_money'],
                                    'type' => 9,
                                    'log_note' => '取消预约续租订单退款',
                                    'order_id' => $vn['id'],
                                    'order_type' => 1,
                                    'createtime' => time(),
                                    'total_order_id' => $order['id']
                                ];
                                PlatformLog::insert($platform_log);
                            } else {
                                Db::rollback();
                                return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                            }
                        }
                    }

                    //当面付订单退款
                    $order_face_payed = $order['order_face_payed'];
                    if ($order_face_payed) {
                        foreach ($order_face_payed as $kf => $vf) {
                            $liquidated_damages = bcmul($cancel_rate, $vf['last_all_money'], 2);
                            $refund_money = bcsub($vf['last_all_money'], $liquidated_damages, 2);
                            if ($merchant['cancel_rate'] > 0 && $liquidated_damages > 0) {
                                //取消订单商家余额增加
                                $merchant_liquidated_money[] = bcmul($refund_money, $merchant['cancel_rate'] / 100, 2);
                            }
                            $vf['refund_money'] = $refund_money;
                            $update = ['status' => 3, 'cancel_time' => time()];
                            $out_refund_no = self::getOutRefundNo('order_face');
                            $vf['out_refund_no'] = $out_refund_no;
                            $res = self::alipayrefund($vf, $user);
                            if ($res['code'] == '10000') {
                                $update['out_refund_no'] = $out_refund_no;
                                $update['refund_id'] = $res['trade_no'];
                                $update['refund_time'] = time();
                                $update['refund_money'] = $res['refund_fee'];
                                $update['liquidated_damages'] = $liquidated_damages;
                                $result = OrderFace::where('id', $vf['id'])->update($update);
                                //写入平台流水
                                $platform_log = [
                                    'user_id' => $user['id'],
                                    'amount' => $vf['refund_money'],
                                    'type' => 11,
                                    'log_note' => '取消预约当面付订单退款',
                                    'order_id' => $vf['id'],
                                    'order_type' => 1,
                                    'createtime' => time(),
                                    'total_order_id' => $order['id']
                                ];
                                PlatformLog::insert($platform_log);
                            } else {
                                Db::rollback();
                                return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                            }
                        }
                    }
                }
            } else {//全扣 即不退款
                //主订单
                $result = self::where('id', $order_id)->update(['status' => 4, 'cancel_time' => time(), 'cancel_type' => $cancel_type, 'cancel_reason' => $cancel_reason, 'liquidated_damages' => $order['last_all_money']]);
                if ($merchant['cancel_rate'] > 0) {
                    //取消订单商家余额增加
                    $merchant_liquidated_money[] = bcmul($order['last_all_money'], $merchant['cancel_rate'] / 100, 2);
                }
                //车状态修改
                MerchantCar::where('id', $order['merchant_car_id'])->update(['car_status' => 1]);
                //换车订单
                $order_change_payed = $order['order_change_payed'];
                if ($order_change_payed) {
                    foreach ($order_change_payed as $kaa => $vaa) {
                        $result = OrderChange::where('id', $vaa['id'])->update(['pay_status' => 3, 'cancel_time' => time(), 'liquidated_damages' => $vaa['last_all_money']]);
                    }
                    if ($merchant['cancel_rate'] > 0) {
                        //取消订单商家余额增加
                        $change_last_all_money = array_column($order_change_payed, 'last_all_money');
                        $merchant_liquidated_money[] = bcmul(array_sum($change_last_all_money), $merchant['cancel_rate'] / 100, 2);
                    }
                }

                //续租订单
                $order_continue_payed = $order['order_continue_payed'];
                if ($order_continue_payed) {
                    foreach ($order_continue_payed as $kbb => $vbb) {
                        $result = OrderContinue::where('id', 'in', implode(',', $continue_ids))->update(['pay_status' => 3, 'cancel_time' => time(), 'liquidated_damages' => $vbb['last_all_money']]);
                    }
                    if ($merchant['cancel_rate'] > 0) {
                        //取消订单商家余额增加
                        $continue_last_all_money = array_column($order_continue_payed, 'last_all_money');
                        $merchant_liquidated_money[] = bcmul(array_sum($continue_last_all_money), $merchant['cancel_rate'] / 100, 2);
                    }
                }

                //当面付订单
                $order_face_payed = $order['order_face_payed'];
                if ($order_face_payed) {
                    foreach ($order_continue_payed as $kcc => $vcc) {
                        $result = OrderFace::where('id', $vcc['id'])->update(['status' => 3, 'cancel_time' => time(), 'liquidated_damages' => $vbb['last_all_money']]);
                    }
                    if ($merchant['cancel_rate'] > 0) {
                        //取消订单商家余额增加
                        $face_last_all_money = array_column($order_face_payed, 'last_all_money');
                        $merchant_liquidated_money[] = bcmul(array_sum($face_last_all_money), $merchant['cancel_rate'] / 100, 2);
                    }
                }
            }

            //其他无偿换车订单
            $other_change_id = OrderChange::where(['is_delete' => 1, 'order_id' => $order['id']])->where('pay_status', 'in', '1,2')->column('id');
            if ($other_change_id) {
                OrderChange::where('id', 'in', implode(',', $other_change_id))->update(['pay_status' => 3, 'cancel_time' => time()]);
            }

            //其他待支付续租订单
            $other_continue_id = OrderContinue::where(['is_delete' => 1, 'order_id' => $order['id']])->where('pay_status', 'in', '1')->column('id');
            if ($other_continue_id) {
                OrderContinue::where('id', 'in', implode(',', $other_continue_id))->update(['pay_status' => 3, 'cancel_time' => time()]);
            }

            //其他待支付当面付订单
            $other_face_id = OrderFace::where(['is_delete' => 1, 'order_id' => $order['id']])->where('status', 'in', '1')->column('id');
            if ($other_face_id) {
                OrderFace::where('id', 'in', implode(',', $other_face_id))->update(['status' => 3, 'cancel_time' => time()]);
            }
            //商家余额增加违约金比例
            if ($merchant_liquidated_money) {
                $merchant_liquidated_money = array_sum($merchant_liquidated_money);
                if ($merchant_liquidated_money > 0) {
                    Merchant::where('id', $merchant['id'])->inc('shop_balance', $merchant_liquidated_money)->update();
                    $balance_log = [
                        'merchant_id' => $merchant['id'],
                        'amount' => $merchant_liquidated_money,
                        'type' => 6,
                        'log_note' => '取消订单扣除违约金获取',
                        'createtime' => time(),
                        'order_id' => $order_id,
                        'order_type' => 1,
                        'total_order_id' => $order_id
                    ];
                    BalanceLog::insert($balance_log);
                }
            }
            $merchant_car = MerchantCar::where(['is_delete' => 1, 'id' => $order['merchant_car_id']])->find();
            $merchant_phone = \app\api\model\Merchant::where(['is_delete' => 1, 'id' => $order['merchant_id']])->value('merchant_phone');
            if ($merchant_phone && $merchant_car) {
                $car_cate = CarCate::where('id', $merchant_car['type_id'])->value('cate_name');
                //向商家发送短信
                $data = [
                    'number' => $order['out_trade_no'],
                    'model' => $car_cate,
                    'car_number' => $order['car_number'],
                    'username' => $user['truename'],
                    'start_time' => date('Y-m-d H:i:s', $order['start_time']),
                    'pick_address' => $order['pick_address'],
                ];
                $res = sendMsg($merchant_phone, $data, 'SMS_464111297');
                //向用户发送短信
                $service_phone = \app\common\model\Config::where('name', 'service_phone')->value('value');
                $data = [
                    'type' => $car_cate,
                    'service' => $service_phone,
                ];
                $res = sendMsg($order['user_phone'], $data, 'SMS_464760133');
            }
            Db::commit();
            return ['status' => 1, 'message' => '请求成功', 'result' => ''];
        } catch (Exception $e) {
            Db::rollback();
            return ['status' => 0, 'message' => $e->getMessage(), 'result' => ''];
        }
    }

    /**
     *  支付成功页面
     */
    public function orderSuccess($requestData, $user)
    {
        $order_id = $requestData['order_id'] ?? 0;
        $order = self::getFind(['id' => $order_id, 'user_id' => $user['id'], 'is_delete' => 1], 'id,shop_name,shop_logo,shop_address,shop_point,start_time,end_time,pick_address,pick_point,return_address,return_point');
        if (!$order) {
            return ['status' => 0, 'message' => '订单不存在', 'result' => ''];
        }
        $order['start_time'] = date('m月d日 H:i', $order['start_time']);
        $order['end_time'] = date('m月d日 H:i', $order['end_time']);
        return ['status' => 1, 'message' => '请求成功', 'result' => $order];
    }

    /**
     *  续租
     */
    public function continue($requestData, $user)
    {
        $type = $requestData['type'] ?? 0;
        $order_id = $requestData['order_id'] ?? 0;
        $merchant_insure_id = $requestData['merchant_insure_id'] ?? 0;
        $end_time = $requestData['end_time'] ?? '';
        if (!$type || !in_array($type, [1, 2]) || !$order_id) {
            return ['status' => 0, 'message' => '参数错误', 'result' => ''];
        }
        if ($type == 2 && (!$merchant_insure_id || !$end_time)) {
            return ['status' => 0, 'message' => '参数错误', 'result' => ''];
        }
        $order = self::where(['user_id' => $user['id'], 'is_delete' => 1, 'id' => $order_id])->whereIn('status', '1,2')->find();
        if (!$order) {
            return ['status' => 0, 'message' => '订单不存在', 'result' => ''];
        }
        $order = $order->toArray();
        if ($order['change_status'] == 2) {
            return ['status' => 0, 'message' => '订单换车中', 'result' => ''];
        }
        if ($order['continue_status'] == 2) {
            $text = Order::fetchContinueStatus($order['continue_status']);
            return ['status' => 0, 'message' => '订单续租' . $text, 'result' => ''];
        }
        if ($order['face_status'] == 2) {
            return ['status' => 0, 'message' => '订单当面付款中', 'result' => ''];
        }
        if ($user['is_certified'] != 3) {
            return ['status' => 0, 'message' => '请先实名认证', 'result' => ''];
        }
        $merchant_car = MerchantCar::with('carss')->field('id,car_id,merchant_car_name,banner,car_price,car_deposit,car_note,car_number,car_label,handle_fee,night_pick_fee,night_return_fee,car_insurance,drive,displacement')->where(['id' => $order['merchant_car_id'], 'merchant_id' => $order['merchant_id'], 'is_delete' => 1, 'status' => 1, 'examine_status' => 2])->find();
        if (!$merchant_car) {
            return ['status' => 0, 'message' => '车辆不存在', 'result' => ''];
        }
        $merchant_car['car_price'] = floatval($merchant_car['car_price']);
        $merchant_car['car_deposit'] = floatval($merchant_car['car_deposit']);
        $merchant_car['handle_fee'] = floatval($merchant_car['handle_fee']);
        $merchant_car['night_pick_fee'] = floatval($merchant_car['night_pick_fee']);
        $merchant_car['night_return_fee'] = floatval($merchant_car['night_return_fee']);
        $merchant_car['banner'] = explode(',', $merchant_car['banner']);
        $car_gear = $merchant_car['car_gear'] == 1 ? '手动' : '自动';
        $label = $merchant_car['car_site'] . '座|' . $merchant_car['car_gate'] . '门|' . $car_gear . '|' . $merchant_car['displacement'];
        $merchant_car['car_sign'] = $label;
        $labels = '';
        if ($merchant_car['car_label']) {
            $labels = Label::where('id', 'in', $merchant_car['car_label'])->column('name');
            $labels = implode(',', $labels);
        }
        $merchant_car['car_label'] = $labels;
        //商家信息
        $merchant = Merchant::getFind(['id' => $order['merchant_id'], 'is_delete' => 1, 'status' => 1, 'examine_status' => 2], 'id,shop_name,shop_logo,Concat(province,city,area,street) as address,service,notice,longitude,latitude,open_time,night_time,coupon_ids');
        if (!$merchant) {
            return ['status' => 0, 'message' => '商家不存在', 'result' => ''];
        }
        if ($type == 1) {//查看
            if (!$merchant_insure_id) {
                $merchant_insure_id = $order['insurance_id'];
            }
            //续租订单
            $last_continue_order = OrderContinue::where(['is_delete' => 1, 'order_id' => $order_id, 'user_id' => $user['id']])->where('pay_status', 'in', '2')->order('createtime', 'desc')->find();
            $start_time = $order['end_time'];
            if ($last_continue_order) {
                $start_time = $last_continue_order['end_time'];
            }
            if (!$end_time) {
                $end_time = bcadd($start_time, 86400 * 2, 0);
            } else {
                $end_time = strtotime($end_time);
            }
            $start_list = [
                'day' => date('m月d日', $start_time),
                'time' => date('H:i', $start_time),
                'week' => $this->week_list[date('w', $start_time)],
                'start_stamp' => $start_time,
                'year_day' => date('Y-m-d', $start_time)
            ];
            $end_list = [
                'day' => date('m月d日', $end_time),
                'time' => date('H:i', $end_time),
                'week' => $this->week_list[date('w', $end_time)],
                'end_stamp' => $end_time,
                'year_day' => date('Y-m-d', $end_time)
            ];
            //租车保障
            $insure_ids = Insure::where(['is_delete' => 1, 'status' => 1])->column('id');
            $insure_list = MerchantCarInsure::field('id,insure_id,price')->with('insures')->where(['is_delete' => 1, 'merchant_car_id' => $merchant_car['id'], 'id' => $order['insurance_id']])->where('insure_id', 'in', $insure_ids)->select()->toArray();
            foreach ($insure_list as $ke => $vl) {
                $vl['active'] = 0;
                if ($merchant_insure_id && $merchant_insure_id == $vl['id']) {
                    $vl['active'] = 1;
                }
                $vl['price'] = floatval($vl['price']);
                $insure_list[$ke] = $vl;
            }
            //保障规则和取消规则
            $config = \app\api\model\Config::where('name', 'in', 'car_guarantee,cancel_time1,cancel_money1,cancel_money2,platform_agreement')->column('value', 'name');
            //天数
            $days = ceil(bcdiv(bcsub($end_time, $start_time, 0), 86400, 2));
            //商家车辆远期价格
            $date_list = createDateRange(date('Y-m-d H:i', $start_time), date('Y-m-d H:i', $end_time));
            $merchant_car_price_list = MerchantCarPrice::field('start_time,end_time,price,days')->where(['is_delete' => 1, 'merchant_car_id' => $order['merchant_car_id']])->where('end_time', '>', time())->select()->toArray();
            $new_date_list = [];
            if ($merchant_car_price_list) {
                foreach ($date_list as $kk => $vv) {
                    $new_date['date'] = $vv;
                    $new_date['price'] = $merchant_car['car_price'];
                    foreach ($merchant_car_price_list as $kkk => $vvv) {
                        if (strtotime($vv) >= $vvv['start_time'] && strtotime($vv) <= $vvv['end_time']) {
                            if ($days < $vvv['days']) {
                                return ['status' => 0, 'message' => '起租天数必须大于' . $vvv['days'], 'result' => ''];
                            }
                            $new_date['price'] = $vvv['price'];
                        }
                    }
                    $new_date_list[] = $new_date;
                }
                $price_list = array_column($new_date_list, 'price');
                $prices = implode(',', $price_list);
                //租车费用
                $rental_money = array_sum($price_list);
            } else {
                $rental_money = bcmul($merchant_car['car_price'], $days, 2);
            }

            if ($rental_money < 0.01) {
                return ['status' => 0, 'message' => '租车费用必须大于0.01', 'result' => ''];
            }
            //判断取还车是否夜间
            $night_time = explode('-', $merchant['night_time']);
            $night_hour_list = getHours($night_time[0], $night_time[1]);
            $end_hour = date('H', $end_time);
            $night_return_fee = 0;
            if (in_array($end_hour, $night_hour_list)) {
                $night_return_fee = $merchant_car['night_return_fee'];
            }
            //手续费
            $handle_fee = 0;
            //保险费用
            $merchant_insurance = MerchantCarInsure::where('id', $merchant_insure_id)->find();
            $insurance = $merchant_insurance['price'] ?? 0;
            $insurance_money = bcmul($insurance, $days, 2);
            //押金
            $car_deposit = 0;
            //总费用
            $all_money = bcadd($rental_money, ($insurance_money + $night_return_fee), 2);
            $result_order = [
                'id' => $order['id'],
                'out_trade_no' => $order['out_trade_no'],
                'price' => floatval($order['price']),
                'start_list' => $start_list,
                'end_list' => $end_list,
                'days' => $days,
                'merchant' => $merchant,
                'merchant_car' => $merchant_car,
                'rental_money' => floatval($rental_money),
                'handle_fee' => floatval($handle_fee),
                'car_deposit' => floatval($car_deposit),
                'insurance_money' => floatval($insurance_money),
                'all_money' => floatval($all_money),
                'insure_list' => $insure_list,
                'config' => $config,
                'night_return_fee' => floatval($night_return_fee)
            ];
            return ['status' => 1, 'message' => '请求成功', 'result' => $result_order];
        } else {
            $end_time = strtotime($end_time);
            $start_time = $order['end_time'];
            $continue_order = OrderContinue::where(['is_delete' => 1, 'user_id' => $user['id'], 'pay_status' => 1, 'order_id' => $order_id])->whereIn('continue_status', '1,2')->count();
            if ($continue_order) {
                return ['status' => 0, 'message' => '订单续租中', 'result' => ''];
            }
            if ($start_time >= $end_time) {
                return ['status' => 0, 'message' => '结束时间不能大于开始时间', 'result' => ''];
            }
            $last_end_time = OrderContinue::where(['is_delete' => 1, 'user_id' => $user['id'], 'order_id' => $order_id, 'continue_status' => 2])->where('pay_status', 'in', '1,2,4')->order('createtime', 'desc')->value('end_time');
            if ($last_end_time && $end_time < $last_end_time) {
                return ['status' => 0, 'message' => '结束时间不能小于该订单最后一次续租时间', 'result' => ''];
            }

            $start_date = date('Y-m-d', $start_time);
            $end_date = date('Y-m-d', $end_time);
            //判断商家营业时间
            $open_time = explode('-', $merchant['open_time']);
            if ($start_time < strtotime($start_date . ' ' . $open_time[0]) || $start_time > strtotime($start_date . ' ' . $open_time[1]) || $end_time < strtotime($end_date . ' ' . $open_time[0]) || $end_time > strtotime($end_date . ' ' . $open_time[1])) {
                return ['status' => 0, 'message' => '商家营业时间：' . $open_time, 'result' => ''];
            }
            //临时下架时间
            $last_time = strtotime("-1 month");
            $merchant_car_time = MerchantCarTime::where(['is_delete' => 1, 'merchant_car_id' => $order['merchant_car_id']])->where('end_time', '>', $last_time)->select();
            foreach ($merchant_car_time as $ke => $vl) {
                $is_time_cross = is_time_cross($vl['start_time'], $vl['end_time'], $start_time, $end_time);
                if ($is_time_cross) {
                    return ['status' => 0, 'message' => '租赁时间段内商家车辆会临时下架', 'result' => ''];
                }
            }

            //天数
            $days = ceil(bcdiv(bcsub($end_time, $start_time, 0), 86400, 2));
            //商家车辆远期价格
            $date_list = createDateRange(date('Y-m-d H:i', $order['start_time']), $requestData['end_time']);
            $merchant_car_price_list = MerchantCarPrice::field('start_time,end_time,price,days')->where(['is_delete' => 1, 'merchant_car_id' => $order['merchant_car_id']])->where('end_time', '>', time())->select()->toArray();
            $new_date_list = [];
            foreach ($date_list as $kk => $vv) {
                $new_date['date'] = $vv;
                $new_date['price'] = $merchant_car['car_price'];
                foreach ($merchant_car_price_list as $kkk => $vvv) {
                    if (strtotime($vv) >= $vvv['start_time'] && strtotime($vv) <= $vvv['end_time']) {
                        if ($days < $vvv['days']) {
                            return ['status' => 0, 'message' => '起租天数必须大于' . $vvv['days'], 'result' => ''];
                        }
                        $new_date['price'] = $vvv['price'];
                    }
                }
                $new_date_list[] = $new_date;
            }
            $price_list = array_column($new_date_list, 'price');
            $prices = implode(',', $price_list);
            //租车费用
            $rental_money = array_sum($price_list);
            //平均单价
            $car_price = bcdiv($rental_money, count($price_list), 2);
            if ($rental_money < 0.01) {
                return ['status' => 0, 'message' => '租车费用必须大于0.01', 'result' => ''];
            }
            //判断取还车是否夜间
            $night_time = explode('-', $merchant['night_time']);
            $night_return_fee = 0;//夜间还车服务费用
            if ($end_time >= strtotime(date('Y-m-d', $end_time) . ' ' . $night_time[0]) && $end_time <= strtotime(date('Y-m-d', $end_time) . ' ' . $night_time[1])) {
                $night_return_fee = $merchant_car['night_return_fee'];
            }
            //手续费
            $handle_fee = 0;
            //保险费用
            $merchant_insurance = MerchantCarInsure::where('id', $merchant_insure_id)->find();
            $insurance = $merchant_insurance['price'] ?? 0;
            $insurance_money = bcmul($insurance, $days, 2);
            //押金
            $car_deposit = 0;
            //总费用
            $all_money = bcadd($rental_money, ($insurance_money + $night_return_fee), 2);
            $change_order = [
                'user_id' => $user['id'],
                'order_id' => $order_id,
                'out_trade_no' => self::getOutTradeNo('order_continue'),
                'merchant_car_id' => $order['merchant_car_id'],
                'merchant_id' => $order['merchant_id'],
                'start_time' => $start_time,
                'end_time' => $end_time,
                'days' => $days,
                'price' => $car_price,
                'rental_money' => $rental_money,
                'deposit' => $car_deposit,
                'all_money' => $all_money,
                'deposit_status' => $car_deposit > 0 ? 1 : 0,
                'send_type' => $order['send_type'],
                'createtime' => time(),
                'insurance' => $insurance_money,
                'insurance_id' => $merchant_insure_id,
                'pay_type' => $order['pay_type'],
                'handle_fee' => $handle_fee,
                'prices' => $prices,
                'last_all_money' => $all_money,
                'night_return_fee' => $night_return_fee
            ];
            Db::startTrans();
            try {
                OrderContinue::insert($change_order);
                self::where('id', $order['id'])->update(['continue_status' => 2]);
                Db::commit();
                return ['status' => 1, 'message' => '请求成功', 'result' => ''];
            } catch (Exception $e) {
                Db::rollback();
                return ['status' => 0, 'message' => $e->getMessage(), 'result' => ''];
            }
        }
    }

    /**
     *  续租订单详情
     */
    public function continueDetail($requestData, $user)
    {
        $id = $requestData['id'] ?? 0;
        $change_order = OrderContinue::field('id,order_id,merchant_id,merchant_car_id,out_trade_no,start_time,end_time,days,price,rental_money,deposit,all_money,pay_status,deposit_status,insurance_id,insurance,insurance_price,handle_fee,continue_status,createtime')->where(['is_delete' => 1, 'user_id' => $user['id'], 'id' => $id])->find();
        if (!$change_order) {
            return ['status' => 0, 'message' => '续租订单不存在', 'result' => ''];
        }
        $change_order['price'] = floatval($change_order['price']);
        $change_order['rental_money'] = floatval($change_order['rental_money']);
        $change_order['deposit'] = floatval($change_order['deposit']);
        $change_order['all_money'] = floatval($change_order['all_money']);
        $change_order['insurance'] = floatval($change_order['insurance']);
        $change_order['insurance_price'] = floatval($change_order['insurance_price']);
        $change_order['handle_fee'] = floatval($change_order['handle_fee']);
        $merchant_car = MerchantCar::with('carss')->where('id', $change_order['merchant_car_id'])->find();
        $car_gear = MerchantCar::fetchCarGear($merchant_car['car_gear']);
        $change_order['car_sign'] = $merchant_car['car_site'] . '座|' . $merchant_car['car_gate'] . '门|' . $car_gear . '|' . $merchant_car['displacement'];
        $change_order['merchant_car_name'] = $merchant_car['merchant_car_name'];
        $change_order['car_number'] = $merchant_car['car_number'];
        $change_order['car_name'] = $merchant_car['car_name'];
        $change_order['car_image'] = $merchant_car['car_image'];
        $res = getDhir($change_order['start_time'], $change_order['end_time']);
        if ($res['d'] > 0) {
            $days_new = $res['h'] > 0 ? $res['d'] . '天' . $res['h'] . '小时' : $res['d'] . '小时';
        } else {
            $days_new = $res['h'] . '小时';
        }
        $change_order['days_new'] = $days_new;
        $merchant_insure = MerchantCarInsure::where('id', $change_order['insurance_id'])->find();
        $change_order['insure_name'] = $merchant_insure['insure_name'];
        $change_order['createtime'] = date('Y-m-d H:i:s', $change_order['createtime']);
        $start_time = [
            'day' => date('m月d日', $change_order['start_time']),
            'time' => date('H:i', $change_order['start_time']),
            'week' => $this->week_list[date('w', $change_order['start_time'])]
        ];
        $change_order['start_time_list'] = $start_time;
        $end_time = [
            'day' => date('m月d日', $change_order['end_time']),
            'time' => date('H:i', $change_order['end_time']),
            'week' => $this->week_list[date('w', $change_order['end_time'])]
        ];
        $change_order['end_time_list'] = $end_time;
        return ['status' => 1, 'message' => '请求成功', 'result' => $change_order];
    }

    /**
     *  当面收费订单详情
     */
    public function faceDetail($requestData, $user)
    {
        $id = $requestData['id'] ?? 0;
        $face_order = OrderFace::field('id,order_id,out_trade_no,all_money,status,type,createtime,content,time_end')->where(['is_delete' => 1, 'user_id' => $user['id'], 'id' => $id])->find();
        if (!$face_order) {
            return ['status' => 0, 'message' => '当面收费订单不存在', 'result' => ''];
        }
        $face_order['all_money'] = floatval($face_order['all_money']);
        $type = FaceCate::where('id', $face_order['type'])->find();
        $face_order['type_name'] = $type['name'] ?? '';
        $face_order['createtime'] = date('Y-m-d H:i:s', $face_order['createtime']);
        $face_order['time_end'] = $face_order['time_end'] ? date('Y-m-d H:i:s', $face_order['time_end']) : '';
        return ['status' => 1, 'message' => '请求成功', 'result' => $face_order];
    }

    /**
     *  续租支付
     */
    public function continuePay($requestData, $user)
    {
        $order_id = $requestData['order_id'] ?? 0;
        $continue_order_id = $requestData['continue_order_id'] ?? 0;
        if (!$order_id || !$continue_order_id) {
            return ['status' => 0, 'message' => '请求错误', 'result' => ''];
        }
        if ($user['is_certified'] != 3) {
            return ['status' => 0, 'message' => '请先实名认证', 'result' => ''];
        }
        $order = self::where(['user_id' => $user['id'], 'is_delete' => 1, 'id' => $order_id])->whereIn('status', '1,2')->find();
        if (!$order) {
            return ['status' => 0, 'message' => '订单不存在', 'result' => ''];
        }
        if ($order['change_status'] == 2) {
            return ['status' => 0, 'message' => '订单换车中', 'result' => ''];
        }
        if ($order['continue_status'] != 3) {
            $text = Order::fetchContinueStatus($order['continue_status']);
            return ['status' => 0, 'message' => '订单续租' . $text, 'result' => ''];
        }
        if ($order['face_status'] == 2) {
            return ['status' => 0, 'message' => '订单当面付款中', 'result' => ''];
        }
        $continue_order = OrderContinue::where(['is_delete' => 1, 'user_id' => $user['id'], 'id' => $continue_order_id, 'order_id' => $order_id, 'pay_status' => 1, 'continue_status' => 2])->find();
        if (!$continue_order) {
            return ['status' => 0, 'message' => '续租订单不存在', 'result' => ''];
        }
        Db::startTrans();
        try {
            //去支付
            if ($order['pay_type'] == 1) {//微信支付
                $result = self::Pay($continue_order, $user, 'continueWechatNotify');
            } else {//支付宝支付
                $result = self::aliPay($continue_order, $user, 'continueAlipayNotify');
            }
            Db::commit();
            if ($result) {
                $result['order_id'] = $order_id;
                return ['status' => 1, 'message' => '请求成功', 'result' => $result];
            } else {
                return ['status' => 0, 'message' => '请求失败', 'result' => ''];
            }
        } catch (Exception $e) {
            Db::rollback();
            return ['status' => 1, 'message' => $e->getMessage(), 'result' => ''];
        }
    }

    /**
     *  换车支付
     */
    public function changePay($requestData, $user)
    {
        $order_id = $requestData['order_id'] ?? 0;
        $change_order_id = $requestData['change_order_id'] ?? 0;
        if (!$order_id || !$change_order_id) {
            return ['status' => 0, 'message' => '请求错误', 'result' => ''];
        }
        if ($user['is_certified'] != 3) {
            return ['status' => 0, 'message' => '请先实名认证', 'result' => ''];
        }
        $order = self::where(['user_id' => $user['id'], 'is_delete' => 1, 'id' => $order_id])->whereIn('status', '1,2')->find();
        if (!$order) {
            return ['status' => 0, 'message' => '订单不存在', 'result' => ''];
        }
        if ($order['continue_status'] == 2 || $order['continue_status'] == 3) {
            return ['status' => 0, 'message' => '订单续租中', 'result' => ''];
        }
        if ($order['change_status'] != 2) {
            $text = Order::fetchChangeStatus($order['change_status']);
            return ['status' => 0, 'message' => '订单换车' . $text, 'result' => ''];
        }
        if ($order['face_status'] == 2) {
            return ['status' => 0, 'message' => '订单当面付款中', 'result' => ''];
        }
        $change_order = OrderChange::where(['is_delete' => 1, 'user_id' => $user['id'], 'id' => $change_order_id, 'order_id' => $order_id, 'pay_status' => 1, 'type' => 2])->find();
        if (!$change_order) {
            return ['status' => 0, 'message' => '换车订单不存在', 'result' => ''];
        }
        if ($change_order['diff_money'] <= 0) {
            return ['status' => 0, 'message' => '换车订单无需支付', 'result' => ''];
        }
        $change_order['all_money'] = $change_order['diff_money'];
        Db::startTrans();
        try {
            //去支付
            if ($order['pay_type'] == 1) {//微信支付
                $result = self::Pay($change_order, $user, 'changeWechatNotify');
            } else {//支付宝支付
                $result = self::aliPay($change_order, $user, 'changeAlipayNotify');
            }
            Db::commit();
            if ($result) {
                $result['order_id'] = $order_id;
                return ['status' => 1, 'message' => '请求成功', 'result' => $result];
            } else {
                return ['status' => 0, 'message' => '请求失败', 'result' => ''];
            }
        } catch (Exception $e) {
            Db::rollback();
            return ['status' => 1, 'message' => $e->getMessage(), 'result' => ''];
        }
    }

    /**
     *  当面付支付
     */
    public function facePay($requestData, $user)
    {
        $order_id = $requestData['order_id'] ?? 0;
        $face_order_id = $requestData['face_order_id'] ?? 0;
        if (!$order_id || !$face_order_id) {
            return ['status' => 0, 'message' => '请求错误', 'result' => ''];
        }
        if ($user['is_certified'] != 3) {
            return ['status' => 0, 'message' => '请先实名认证', 'result' => ''];
        }
        $order = self::where(['user_id' => $user['id'], 'is_delete' => 1, 'id' => $order_id])->whereIn('status', '1,2')->find();
        if (!$order) {
            return ['status' => 0, 'message' => '订单不存在', 'result' => ''];
        }
        if ($order['continue_status'] == 2 || $order['continue_status'] == 3) {
            return ['status' => 0, 'message' => '订单续租中', 'result' => ''];
        }
        if ($order['change_status'] == 2) {
            return ['status' => 0, 'message' => '订单换车中', 'result' => ''];
        }
        if ($order['face_status'] != 2) {
            $text = Order::fetchFaceStatus($order['face_status']);
            return ['status' => 0, 'message' => '订单当面付' . $text, 'result' => ''];
        }
        $face_order = OrderFace::where(['is_delete' => 1, 'user_id' => $user['id'], 'id' => $face_order_id, 'order_id' => $order_id, 'status' => 1])->find()->toArray();
        if (!$face_order) {
            return ['status' => 0, 'message' => '当面付订单不存在', 'result' => ''];
        }
        Db::startTrans();
        try {
            //去支付
            if ($order['pay_type'] == 1) {//微信支付
                $result = self::Pay($face_order, $user, 'faceWechatNotify');
            } else {//支付宝支付
                $result = self::aliPay($face_order, $user, 'faceAlipayNotify');
            }
            Db::commit();
            if ($result) {
                $result['order_id'] = $order_id;
                return ['status' => 1, 'message' => '请求成功', 'result' => $result];
            } else {
                return ['status' => 0, 'message' => '请求失败', 'result' => ''];
            }
        } catch (Exception $e) {
            Db::rollback();
            return ['status' => 1, 'message' => $e->getMessage(), 'result' => ''];
        }
    }

    /**
     *  换车总退款申请
     */
    public function changeRefund($requestData, $user)
    {
        $order_id = $requestData['order_id'] ?? 0;
        if (!$order_id) {
            return ['status' => 0, 'message' => '请求错误', 'result' => ''];
        }
        if ($user['is_certified'] != 3) {
            return ['status' => 0, 'message' => '请先实名认证', 'result' => ''];
        }
        $order = self::where(['user_id' => $user['id'], 'is_delete' => 1, 'id' => $order_id])->find();
        if (!$order) {
            return ['status' => 0, 'message' => '订单不存在', 'result' => ''];
        }
        if ($order['status'] != 3) {
            $text = Order::fetchStatus($order['status']);
            return ['status' => 0, 'message' => '订单' . $text, 'result' => ''];
        }
        if ($order['continue_status'] == 2 || $order['continue_status'] == 3) {
            return ['status' => 0, 'message' => '订单续租中', 'result' => ''];
        }
        if ($order['change_status'] == 2) {
            return ['status' => 0, 'message' => '订单换车中', 'result' => ''];
        }
        if ($order['face_status'] == 2) {
            return ['status' => 0, 'message' => '订单当面付中', 'result' => ''];
        }
        if ($order['refund_status'] == 2 || $order['refund_status'] == 3) {
            $text = Order::fetchRefundStatus($order['refund_status']);
            return ['status' => 0, 'message' => '订单换车退款' . $text, 'result' => ''];
        }
        if ($order['all_change_refund_money'] == 0) {
            return ['status' => 0, 'message' => '订单换车应退金额为0', 'result' => ''];
        }
        $refund_order = [
            'user_id' => $user['id'],
            'merchant_id' => $order['merchant_id'],
            'order_id' => $order['id'],
            'out_trade_no' => self::getOutTradeNo('order_refund'),
            'all_money' => $order['all_change_refund_money'],
            'createtime' => time()
        ];
        Db::startTrans();
        try {
            $result = OrderRefund::insertGetId($refund_order);
            Order::where('id', $order_id)->update(['refund_status' => 2]);
            Db::commit();
            if ($result) {
                $refund_order['order_id'] = $order_id;
                $refund_order['id'] = $result;
                return ['status' => 1, 'message' => '请求成功', 'result' => $refund_order];
            } else {
                return ['status' => 0, 'message' => '请求失败', 'result' => ''];
            }
        } catch (Exception $e) {
            Db::rollback();
            return ['status' => 1, 'message' => $e->getMessage(), 'result' => ''];
        }
    }

    //微信小程序支付调用
    public static function Pay($order, $user, $notify_url = 'orderNotify')
    {
        $config = \think\facade\Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $result = $app->order->unify([
            'body' => '预约下单',
            'out_trade_no' => $order['out_trade_no'],
            'total_fee' => $order['all_money'] * 100,
//            'total_fee' => 1,
            'notify_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/api/applets.notify/' . $notify_url,
            'trade_type' => 'JSAPI',
            'openid' => $user['openid']
        ]);
        if ($result['return_code'] != "SUCCESS" || $result['result_code'] != 'SUCCESS') {
            return false;
        }
        $config = $jssdk->bridgeConfig($result['prepay_id'], false);
        if (!$config) {
            return false;
        }
        return $config;
    }

    //支付宝小程序支付
    public static function aliPay($order, $user, $notify_url = 'orderAlipayNotify')
    {
        $refund_money = $order['refund_money'];
//        $refund_money = 0.01;
        $notify_url = 'https://' . $_SERVER['HTTP_HOST'] . '/api/applets.notify/' . $notify_url;
        alipayFactory::setOptions(getOption());
        $result = alipayFactory::payment()->common()->asyncNotify($notify_url)->create("预约下单", $order['out_trade_no'], $order['refund_money'], $user['alipayid']);
        if (!$result) {
            return false;
        }
        if ($result->code != 10000) {
            return false;
            $result->msg . "，" . $result->sub_msg . PHP_EOL;
        }
        $return_result = json_decode($result->httpBody, true);
        return $return_result['alipay_trade_create_response'];
    }

    //微信退款
    public static function refund($order, $user)
    {
        $config = \think\facade\Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($order['out_trade_no'], $order['out_refund_no'], $order['all_money'] * 100, $order['refund_money'] * 100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '取消订单退款',
        ]);
//        $result = $app->refund->byOutTradeNumber($order['out_trade_no'], $order['out_refund_no'], 1, 1, [
//            // 可在此处传入其他参数，详细参数见微信支付文档
//            'refund_desc' => '取消订单退款',
//        ]);
        return $result;
    }

    //支付宝退款
    public static function alipayRefund($order, $user)
    {
        alipayFactory::setOptions(getOption());
        $result = alipayFactory::payment()->common()->refund($order['out_trade_no'], $order['all_money']);
        if (!$result) {
            return false;
        }
        if ($result->code != 10000) {
            return false;
            $result->msg . "，" . $result->sub_msg . PHP_EOL;
        }
        $return_result = json_decode($result->httpBody, true);
        return $return_result['alipay_trade_refund_response'];
    }

    //生成唯一订单号
    public static function getOutTradeNo($table = 'order')
    {
        if ($table == 'order_change') {
            $act_type = 6;
        } elseif ($table == 'order_continue') {
            $act_type = 7;
        } elseif ($table == 'order_face') {
            $act_type = 8;
        } elseif ($table == 'order_refund') {
            $act_type = 13;
        } else {
            $act_type = 1;
        }
        $out_trade_no = sys_create_orderno($act_type);
        $order = Db::name($table)->where('out_trade_no', $out_trade_no)->count();
        if ($order) {
            self::getOutTradeNo($act_type);
        }
        return $out_trade_no;
    }

    //生成唯一退款号
    public static function getOutRefundNo($table = 'order')
    {
        if ($table == 'order_change') {
            $act_type = 10;
        } elseif ($table == 'order_continue') {
            $act_type = 11;
        } elseif ($table == 'order_face') {
            $act_type = 12;
        } elseif ($table == 'order_refund') {
            $act_type = 13;
        } else {
            $act_type = 4;
        }
        $out_refund_no = sys_create_orderno($act_type);
        $order = Db::name($table)->where('out_refund_no', $out_refund_no)->count();
        if ($order) {
            self::getOutRefundNo($act_type);
        }
        return $out_refund_no;
    }

    //商家首页订单信息统计
    public static function orderInfo($merchant_id)
    {
        //已预约订单数
        $pay_num = Order::where(['is_delete' => 1, 'merchant_id' => $merchant_id, 'status' => 1])->count();
        //用车中
        $use_num = Order::where(['is_delete' => 1, 'merchant_id' => $merchant_id, 'status' => 2])->count();
        //已完成
        $finish_num = Order::where(['is_delete' => 1, 'merchant_id' => $merchant_id, 'status' => 3])->count();
        //已取消
        $cancel_num = Order::where(['is_delete' => 1, 'merchant_id' => $merchant_id, 'status' => 4])->count();
        //车辆续租
        $continue_num = Order::field('id')->withCount('order_continue_payed')->where(['is_delete' => 1, 'merchant_id' => $merchant_id])->where('status', 'in', '1,2,3')->having('order_continue_payed_count > 0')->select()->toArray();
        $continue_num = count($continue_num);
        $data = [
            'pay_num' => $pay_num,
            'use_num' => $use_num,
            'finish_num' => $finish_num,
            'cancel_num' => $cancel_num,
            'continue_num' => $continue_num,
        ];
        return $data;
    }

    /**
     * 获取列表
     * @param array $where
     * @param string $field
     * @param int $page
     * @param int $limit
     * @return Driver[]|array|\think\Collection
     */
    public static function getList($where = [], $field = '*', $order = 'createtime desc', $page = 1, $limit = 10)
    {
        if ($page) {
            return self::where($where)->field($field)->order('id', 'desc')->order($order)->page($page, $limit)->select();
        } else {
            return self::where($where)->field($field)->order('id', 'desc')->select();
        }
    }

    /**
     * 获取单条
     * @param array $where
     * @param string $field
     * @return Driver|array|mixed|\think\Model|null
     */
    public static function getFind($where = [], $field = '*')
    {
        return self::where($where)->field($field)->find();
    }

    //订单状态处理
    public static function fetchStatus($status = null)
    {
        $data = [
            1 => '已预约',
            2 => '用车中',
            3 => '已完成',
            4 => '已取消',
        ];
        if (isset($data[$status])) {
            return $data[$status];
        } else {
            return $data;
        }
    }

    //换车状态处理
    public static function fetchChangeStatus($change_status = null)
    {
        $data = [
            1 => '未换车',
            2 => '换车中',
            3 => '换车结束',
            4 => '已取消',
        ];
        if (isset($data[$change_status])) {
            return $data[$change_status];
        } else {
            return $data;
        }
    }

    //续租状态处理
    public static function fetchContinueStatus($continue_status = null)
    {
        $data = [
            1 => '未续租',
            2 => '申请中',
            3 => '已同意',
            4 => '已支付',
            5 => '已拒绝',
        ];
        if (isset($data[$continue_status])) {
            return $data[$continue_status];
        } else {
            return $data;
        }
    }

    //当面付状态处理
    public static function fetchFaceStatus($face_status = null)
    {
        $data = [
            1 => '无',
            2 => '待支付',
            3 => '已支付',
            4 => '已取消',
        ];
        if (isset($data[$face_status])) {
            return $data[$face_status];
        } else {
            return $data;
        }
    }

    //押金状态处理
    public static function fetchDepositStatus($status = null)
    {
        $data = [
            0 => '无押金',
            1 => '待退还',
            2 => '已原路退还',
        ];
        if (isset($data[$status])) {
            return $data[$status];
        } else {
            return $data;
        }
    }

    //押金方式处理
    public static function fetchDepositType($deposit_type = null)
    {
        $data = [
            1 => '门店预授权',
            2 => '门店信用免押',
        ];
        if (isset($data[$deposit_type])) {
            return $data[$deposit_type];
        } else {
            return $data;
        }
    }

    //取车方式
    public static function fetchSendType($status = null)
    {
        $data = [
            1 => '到店自取',
            2 => '送车上门',
        ];
        if (isset($data[$status])) {
            return $data[$status];
        } else {
            return $data;
        }
    }

    //换车退款状态处理
    public static function fetchRefundStatus($refund_status = null)
    {
        $data = [
            1 => '未申请',
            2 => '审核中',
            3 => '已同意',
            4 => '已拒绝',
        ];
        if (isset($data[$refund_status])) {
            return $data[$refund_status];
        } else {
            return $data;
        }
    }

    //订单退款状态
    public static function fetchOrderRefundStatus($order_refund_status = null)
    {
        $data = [
            1 => '未申请',
            2 => '审核中',
            3 => '已通过',
            4 => '已拒绝',
        ];
        if (isset($data[$order_refund_status])) {
            return $data[$order_refund_status];
        } else {
            return $data;
        }
    }

    //取消类型处理
    public static function fetchCancelType($cancel_type = null)
    {
        $data = [
            1 => '行程有变',
            2 => '不想租了',
            3 => '重新下单',
            4 => '价格原因',
            5 => '其他原因',
        ];
        if (isset($data[$cancel_type])) {
            return $data[$cancel_type];
        } else {
            return $data;
        }
    }

    //已支付和已退款的换车订单
    public function orderChangePay()
    {
        return $this->hasMany('order_change', 'order_id', 'id')->field('id,order_id,merchant_car_id,type,out_trade_no,price,all_money,diff_money,deposit_status,other_number,deposit,handle_fee,rental_money,pay_status,createtime,last_all_money,refund_money')->where("is_delete=1 and pay_status in (2,4)")->order('createtime', 'desc');
    }

    //已支付的有偿换车订单
    public function orderChangePayed()
    {
        return $this->hasMany('order_change', 'order_id', 'id')->field('id,order_id,out_trade_no,rental_money,all_money,diff_money,deposit_status,deposit,pay_status,createtime,last_all_money,refund_money')->where("is_delete=1 and type=2 and pay_status in (2) and diff_money>0")->order('createtime', 'desc');;
    }

    //待支付的换车订单
    public function orderChangeUnpay()
    {
        return $this->hasOne('order_change', 'order_id', 'id')->field('id,order_id,out_trade_no,rental_money,all_money,diff_money,deposit,deposit_status,pay_status,createtime,last_all_money,refund_money')->where("is_delete=1 and type=2 and pay_status in (1)")->order('createtime', 'desc');;
    }

    //所有续租订单
    public function orderContinue()
    {
        return $this->hasMany('order_continue', 'order_id', 'id')->field('id,order_id,out_trade_no,rental_money,all_money,deposit_status,pay_status,continue_status,createtime,last_all_money,refund_money')->where("is_delete=1")->order('createtime', 'desc');
    }

    //已支付和已退款的续租订单
    public function orderContinuePay()
    {
        return $this->hasMany('order_continue', 'order_id', 'id')->field('id,order_id,out_trade_no,merchant_car_id,rental_money,all_money,deposit_status,end_time,pay_status,continue_status,createtime,last_all_money,refund_money')->where("is_delete=1 and pay_status in (2,4) and continue_status in (2)")->order('createtime', 'desc');;
    }

    //已支付的续租订单
    public function orderContinuePayed()
    {
        return $this->hasMany('order_continue', 'order_id', 'id')->field('id,order_id,out_trade_no,rental_money,all_money,deposit_status,pay_status,continue_status,createtime,last_all_money,refund_money')->where("is_delete=1 and pay_status in (2) and continue_status in (2)")->order('createtime', 'desc');;
    }

    //待支付的续租订单
    public function orderContinueUnpay()
    {
        return $this->hasOne('order_continue', 'order_id', 'id')->field('id,order_id,out_trade_no,rental_money,all_money,deposit_status,pay_status,continue_status,createtime,last_all_money,refund_money')->where("is_delete=1 and pay_status in (1) and continue_status in (1,2)")->order('createtime', 'desc');;
    }

    //所有当面付订单
    public function orderFace()
    {
        return $this->hasMany('order_face', 'order_id', 'id')->field('id,order_id,out_trade_no,all_money,createtime,status,time_end,content,type,last_all_money,refund_money')->where("is_delete=1")->order('createtime', 'desc');
    }

    //已支付和已退款的当面付订单
    public function orderFacePay()
    {
        return $this->hasMany('order_face', 'order_id', 'id')->field('id,order_id,out_trade_no,all_money,status,createtime,status,last_all_money')->where("is_delete=1 and status in (2,4)")->order('createtime', 'desc');;
    }

    //已支付当面付订单
    public function orderFacePayed()
    {
        return $this->hasMany('order_face', 'order_id', 'id')->field('id,order_id,out_trade_no,all_money,status,createtime,status,last_all_money')->where("is_delete=1 and status in (2)")->order('createtime', 'desc');;
    }

    //待支付的当面付订单
    public function orderFaceUnpay()
    {
        return $this->hasOne('order_face', 'order_id', 'id')->field('id,order_id,out_trade_no,all_money,status,createtime,status,last_all_money')->where("is_delete=1 and status in (1)")->order('createtime', 'desc');;
    }

    //驾驶人
    public function drivers()
    {
        return $this->hasOne('driver', 'id', 'driver_id')->field('driver_name,driver_number')->joinType('left');
    }
}
